diff --git a/packages/ui5-tooling-modules/lib/util.js b/packages/ui5-tooling-modules/lib/util.js index ec6056d0..a7b82efd 100755 --- a/packages/ui5-tooling-modules/lib/util.js +++ b/packages/ui5-tooling-modules/lib/util.js @@ -389,6 +389,20 @@ function findPackageJson(modulePath) { return pkgJsonFile; } +/** + * converts a wildcard pattern to a regular expression + * @param {string} pattern the pattern to convert + * @returns {RegExp} the regular expression + */ +function wildcardToRegex(pattern) { + // escape special characters + const escapedPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&"); + // replace the wildcard with a capture group + const regexPattern = escapedPattern.replace(/\*/g, "(.*)"); + // return the regular expression + return new RegExp(`^${regexPattern}$`); +} + // the utiltiy module module.exports = function (log, projectInfo) { /** @@ -815,9 +829,7 @@ module.exports = function (log, projectInfo) { } else { // Implementation of the Node.js Package Entry Points mechanism // https://nodejs.org/api/packages.html#package-entry-points - let pkgJsonFile, - relativeModulePath, - isEntryModule = true; + let pkgJsonFile, relativeModulePath; // when resolving absolute files we lookup the package.json in the parent dirs // for later resolution of the module path (e.g. the mapping in browsers field) @@ -830,16 +842,17 @@ module.exports = function (log, projectInfo) { if (modulePath === undefined) { modulePath = getModulePathWithExtension(`${moduleName}${path.sep}index`); } + // determine the relative module path to the package.json as the module resolution + // below resolves and maps the module path relative to the package.json only + if (modulePath) { + relativeModulePath = path.relative(path.dirname(pkgJsonFile), modulePath)?.replace(/\\/g, "/"); + } } else { // lookup the package.json with the npm package name const [, npmPackage, , , relModulePath] = npmPackageScopeRegEx.exec(moduleName) || []; pkgJsonFile = findDependency(`${npmPackage}/package.json`, cwd, extendedDepPaths); - // short track if the module exists relative to the package.json - // we can skip the resolution using the package.json fields to find the module + // short track to derive the relative module path relative to the package.json if (pkgJsonFile && relModulePath) { - const rootPath = path.dirname(pkgJsonFile); - modulePath = getModulePathWithExtension(path.join(rootPath, relModulePath)); // undefined if it doesn't exist - isEntryModule = false; relativeModulePath = relModulePath; } } @@ -851,90 +864,141 @@ module.exports = function (log, projectInfo) { const rootPath = path.dirname(pkgJsonFile); const pkgJson = getPackageJson(pkgJsonFile); - // entry modules must be resolved from the package.json fields - if (isEntryModule && modulePath === undefined) { - // exports first - if (pkgJson.exports) { - const exportsField = pkgJson.exports[relativeModulePath ? `./${relativeModulePath}` : "."]; - let main; - if (typeof (main = exportsField?.browser?.default) === "string") { - //console.log("##################", moduleName, "exports[.][browser][default]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = exportsField?.import?.default) === "string") { - //console.log("##################", moduleName, "exports[.][import][default]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = exportsField?.import) === "string") { - //console.log("##################", moduleName, "exports[.][import]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = pkgJson.exports?.import) === "string") { - //console.log("##################", moduleName, "exports[import]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = exportsField?.require?.default) === "string") { - //console.log("##################", moduleName, "exports[.][require][default]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = exportsField?.require) === "string") { - //console.log("##################", moduleName, "exports[.][require]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = pkgJson.exports?.require) === "string") { - //console.log("##################", moduleName, "exports[require]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = exportsField?.default) === "string") { - //console.log("##################", moduleName, "exports[.][default]", main); - modulePath = path.join(rootPath, main); - } else if (typeof (main = exportsField) === "string") { - //console.log("##################", moduleName, "exports[.]", main); - modulePath = path.join(rootPath, main); - } else if (Array.isArray((main = pkgJson.exports["."]))) { - //console.log("##################", moduleName, "exports[.][]", main.pop()); - const entry = main.pop(); - if (typeof entry?.import?.default === "string") { - modulePath = path.join(rootPath, entry.import.default); - } else if (typeof entry?.require?.default === "string") { - modulePath = path.join(rootPath, entry.require.default); - } else if (typeof entry?.default === "string") { - modulePath = path.join(rootPath, entry.default); - } else { - //console.error("#### UNKNOWN CASE ####", "exports[.]", moduleName, JSON.stringify(entry)); - } + // all modules must be resolved from the package.json fields if available + // Hints about package.json exports resolution: + // - https://nodejs.org/api/packages.html#packages_subpath_exports + // - https://github.com/rollup/plugins/blob/master/packages/node-resolve/src/package/resolvePackageExports.ts + // - https://webpack.js.org/guides/package-exports/ + + // conditions means that exports is an object without any entry starting with a dot + // mappins means that exports is an object having no conditions + // conditions and mappings are mutually exclusive + const isConditions = (exports) => { + return exports && !Object.keys(exports).some((key) => key.startsWith(".")); + }; + const isMappings = (exports) => { + return exports && !isConditions(exports); + }; + + // the conditions and mappings to resolve the module path + const communityConditions = ["browser", "production" /*, "development"*/]; // could be injected from outside + const mainModuleConditions = ["esnext", "module", "main"]; + const resolveConditions = [...communityConditions, ...mainModuleConditions, "import", "require", "default"]; // require is just the fallback! + + // helper to resolve the target of a mapping: + // - if the target is a string it is returned (and if needed the wildcard is replaced) + // - if the target is an array the first resolved target is returned + // - if the target is an object the first resolved target of the conditions is returned + const resolveTarget = (target, wildcardMatch) => { + if (typeof target === "string") { + if (!wildcardMatch) { + return target; } else { - //console.error("#### UNKNOWN CASE ####", "exports", moduleName, JSON.stringify(pkgJson.exports)); + // replace the wildcard with the matched wildcard: + // determine the value of the wildcard in the exports field + return target.replace(/\*/g, wildcardMatch); + } + } else if (Array.isArray(target)) { + // resolve the target from the array of targets + for (const entry of target) { + const resolved = resolveTarget(entry, wildcardMatch); + if (resolved) { + return resolved; + } + } + } else if (target && typeof target === "object") { + // resolve the target of the conditions + for (const condition of resolveConditions) { + if (condition in target) { + let resolved = resolveTarget(target[condition], wildcardMatch); + if (resolved) { + return resolved; + } + } } - } else if (typeof pkgJson.browser === "string") { - //console.log("##################", moduleName, "browser", pkgJson.browser); - modulePath = path.join(rootPath, pkgJson.browser); - } else if (typeof pkgJson.module === "string") { - //console.log("##################", moduleName, "module", pkgJson.module); - modulePath = path.join(rootPath, pkgJson.module); - } else if (typeof pkgJson.main === "string") { - //console.log("##################", moduleName, "main", pkgJson.main); - modulePath = path.join(rootPath, pkgJson.main); + // if no condition matches, check for a wildcard match + // which is typically a path mapping in the exports field + if (wildcardMatch in target) { + return target[wildcardMatch]; + } + } + }; + + // helper to resolve the given subpath from the exports field of the package.json + const resolveExports = (exports, subPath) => { + if (subPath.indexOf("*") === -1 && exports[subPath]) { + // no wildcard in the subPath and the subPath is a direct mapping + let resolved = exports[subPath]; + if (typeof resolved === "object") { + resolved = resolveTarget(resolved); + } + return resolved; } else { - // no configuration found, we lookup the index module - modulePath = getModulePathWithExtension(path.join(rootPath, "index")); + // sort the export keys by the position of the wildcard + const exportKeys = Object.keys(exports) + .filter((v) => v.indexOf("*") !== -1) + .sort((a, b) => { + return b.indexOf("*") - a.indexOf("*"); + }); + // helper to lookup the first match for the subPath + const findMatch = (exportKeys, subPath) => { + for (const key of exportKeys) { + const re = wildcardToRegex(key); + const match = re.exec(subPath); + if (match) { + return { target: exports[key], wildcardMatch: match[1] }; + } + } + }; + // lookup the first match for the subPath + const match = findMatch(exportKeys, subPath); + if (match) { + let resolved = resolveTarget(match.target, match.wildcardMatch); + // check if another mapping is required (e.g. ./* to ./dist/* to ./dist/prod/*) + const resolvedMatch = findMatch(exportKeys, resolved); + if (resolvedMatch?.target !== match.target) { + resolved = resolveExports(exports, resolved); + } + return resolved; + } } - } - - // if the package.json has a browser field we try to map the module path - // (a false value in the browser field means the module should be ignored) - if (typeof pkgJson.browser === "object") { - //console.log("##################", moduleName, "browser", pkgJson.browser); - const mappings = - packageJsonCache[pkgJsonFile + "~mappings"] || - Object.fromEntries( - Object.entries(pkgJson.browser) - .filter(([key, value]) => { - return value !== false; // these modules should ideally be ignored => maybe we make them undefined - }) - .map(([key, value]) => { - return [path.join(rootPath, key), path.join(rootPath, value)]; - }), - ); - if (!packageJsonCache[pkgJsonFile + "~mappings"]) { - packageJsonCache[pkgJsonFile + "~mappings"] = mappings; + return subPath; + }; + + // lookup the module path from the package.json browser or exports field + const { browser, exports } = pkgJson; + let subPath = relativeModulePath ? `./${relativeModulePath}` : "."; + + let mainExport; + if (subPath === ".") { + // if the module is the main module of the package + if (typeof browser === "string") { + // if a browser field is a string value in the package.json + // the main module is defined in the browser field + // (an object value means it is a mapping used below!) + mainExport = browser; + } else if (typeof exports === "string" || Array.isArray(exports) || isConditions(exports)) { + // if exports is a string, an array or an object with conditions + // the main module is defined by the exports field + mainExport = exports; + } else if (isMappings(exports)) { + // if exports is an object with mappings it is defined in the "." exports field + mainExport = exports["."]; + } else { + // lookup the entry modules in the package.json root (esnext, module, main, ...) + mainExport = pkgJson; } - //console.log("##################", "before ", modulePath); - modulePath = mappings[modulePath] || modulePath; - //console.log("##################", "after ", modulePath); + const resolved = resolveTarget(mainExport); + modulePath = resolved ? path.join(rootPath, resolved) : undefined; + } else if (isMappings(browser)) { + // if the module is a sub module of the package and the package has a browser field + // which contains + const resolved = resolveExports(browser, subPath); + modulePath = resolved ? path.join(rootPath, resolved) : undefined; + } else if (isMappings(exports)) { + // if the module is a sub module of the package + const resolved = resolveExports(exports, subPath); + modulePath = resolved ? path.join(rootPath, resolved) : undefined; } // check for the module path exists and is a file @@ -1149,11 +1213,12 @@ module.exports = function (log, projectInfo) { // 4) is no UI5 module if (modulePath) { if (/\.(m|c)?js$/.test(path.extname(modulePath).toLowerCase()) && !shouldSkipTransform(moduleName) && !(await shouldSkipModule(modulePath))) { - const module = bundleInfo.addModule({ + const module = { name: moduleName, path: modulePath, lastModified: new Date((await stat(modulePath)).mtime).getTime(), - }); + }; + bundleInfo.addModule(module); lastModified = Math.max(lastModified, module.lastModified); } else { bundleInfo.addResource(that.getResource(moduleName, { cwd, depPaths })); diff --git a/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js index 28434ed2..5eccecf1 100644 --- a/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js +++ b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js @@ -1,7 +1,286 @@ -sap.ui.define(['ui5/ecosystem/demo/app/resources/index3'], (function (index) { 'use strict'; +sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/trace-api'], (function (exports, traceApi) { 'use strict'; - let exp = index.src?.default || index.src || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const consoleMap = [ + { n: 'error', c: 'error' }, + { n: 'warn', c: 'warn' }, + { n: 'info', c: 'info' }, + { n: 'debug', c: 'debug' }, + { n: 'verbose', c: 'trace' }, + ]; + /** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ + class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function (...args) { + if (console) { + // Some environments only expose the console when the F12 developer console is open + // eslint-disable-next-line no-console + let theFunc = console[funcName]; + if (typeof theFunc !== 'function') { + // Not all environments support all functions + // eslint-disable-next-line no-console + theFunc = console.log; + } + // One last final check + if (typeof theFunc === 'function') { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } + } - return exp; + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; + const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; + const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; + const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); + const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; + /** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ + function validateKey(key) { + return VALID_KEY_REGEX.test(key); + } + /** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ + function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const MAX_TRACE_STATE_ITEMS = 32; + const MAX_TRACE_STATE_LEN = 512; + const LIST_MEMBERS_SEPARATOR = ','; + const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; + /** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ + class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if (validateKey(key) && validateValue(value)) { + agg.set(key, value); + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + function createTraceState(rawTraceState) { + return new TraceStateImpl(rawTraceState); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Default export. + var defaultExport = { + context: traceApi.context, + diag: traceApi.diag, + metrics: traceApi.metrics, + propagation: traceApi.propagation, + trace: traceApi.trace, + }; + + let exp = defaultExport?.default || defaultExport || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} + + Object.defineProperty(exports, "DiagLogLevel", { + enumerable: true, + get: function () { return traceApi.DiagLogLevel; } + }); + exports.INVALID_SPANID = traceApi.INVALID_SPANID; + exports.INVALID_SPAN_CONTEXT = traceApi.INVALID_SPAN_CONTEXT; + exports.INVALID_TRACEID = traceApi.INVALID_TRACEID; + exports.ProxyTracer = traceApi.ProxyTracer; + exports.ProxyTracerProvider = traceApi.ProxyTracerProvider; + exports.ROOT_CONTEXT = traceApi.ROOT_CONTEXT; + Object.defineProperty(exports, "SamplingDecision", { + enumerable: true, + get: function () { return traceApi.SamplingDecision; } + }); + Object.defineProperty(exports, "SpanKind", { + enumerable: true, + get: function () { return traceApi.SpanKind; } + }); + Object.defineProperty(exports, "SpanStatusCode", { + enumerable: true, + get: function () { return traceApi.SpanStatusCode; } + }); + Object.defineProperty(exports, "TraceFlags", { + enumerable: true, + get: function () { return traceApi.TraceFlags; } + }); + Object.defineProperty(exports, "ValueType", { + enumerable: true, + get: function () { return traceApi.ValueType; } + }); + exports.baggageEntryMetadataFromString = traceApi.baggageEntryMetadataFromString; + exports.context = traceApi.context; + exports.createContextKey = traceApi.createContextKey; + exports.createNoopMeter = traceApi.createNoopMeter; + exports.defaultTextMapGetter = traceApi.defaultTextMapGetter; + exports.defaultTextMapSetter = traceApi.defaultTextMapSetter; + exports.diag = traceApi.diag; + exports.isSpanContextValid = traceApi.isSpanContextValid; + exports.isValidSpanId = traceApi.isValidSpanId; + exports.isValidTraceId = traceApi.isValidTraceId; + exports.metrics = traceApi.metrics; + exports.propagation = traceApi.propagation; + exports.trace = traceApi.trace; + exports.DiagConsoleLogger = DiagConsoleLogger; + exports.createTraceState = createTraceState; + exports.default = exp; + + Object.defineProperty(exports, '__esModule', { value: true }); })); diff --git a/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/sdk-trace-web.js b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/sdk-trace-web.js index dca2a0ad..9b2ad605 100644 --- a/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/sdk-trace-web.js +++ b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/sdk-trace-web.js @@ -1,4 +1,4 @@ -sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function (exports, index) { 'use strict'; +sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/trace-api'], (function (exports, traceApi) { 'use strict'; /* * Copyright The OpenTelemetry Authors @@ -15,7 +15,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var SUPPRESS_TRACING_KEY = index.src.createContextKey('OpenTelemetry SDK Context Key SUPPRESS_TRACING'); + const SUPPRESS_TRACING_KEY = traceApi.createContextKey('OpenTelemetry SDK Context Key SUPPRESS_TRACING'); function suppressTracing(context) { return context.setValue(SUPPRESS_TRACING_KEY, true); } @@ -38,44 +38,42 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var BAGGAGE_KEY_PAIR_SEPARATOR = '='; - var BAGGAGE_PROPERTIES_SEPARATOR = ';'; - var BAGGAGE_ITEMS_SEPARATOR = ','; + const BAGGAGE_KEY_PAIR_SEPARATOR = '='; + const BAGGAGE_PROPERTIES_SEPARATOR = ';'; + const BAGGAGE_ITEMS_SEPARATOR = ','; // Name of the http header used to propagate the baggage - var BAGGAGE_HEADER = 'baggage'; + const BAGGAGE_HEADER = 'baggage'; // Maximum number of name-value pairs allowed by w3c spec - var BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; + const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; // Maximum number of bytes per a single name-value pair allowed by w3c spec - var BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; + const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; // Maximum total length of all name-value pairs allowed by w3c spec - var BAGGAGE_MAX_TOTAL_LENGTH = 8192; + const BAGGAGE_MAX_TOTAL_LENGTH = 8192; - var __read$6 = (this && this.__read) || function (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; - }; + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ function serializeKeyPairs(keyPairs) { - return keyPairs.reduce(function (hValue, current) { - var value = "" + hValue + (hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : '') + current; + return keyPairs.reduce((hValue, current) => { + const value = `${hValue}${hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''}${current}`; return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value; }, ''); } function getKeyPairs(baggage) { - return baggage.getAllEntries().map(function (_a) { - var _b = __read$6(_a, 2), key = _b[0], value = _b[1]; - var entry = encodeURIComponent(key) + "=" + encodeURIComponent(value.value); + return baggage.getAllEntries().map(([key, value]) => { + let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`; // include opaque metadata if provided // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation if (value.metadata !== undefined) { @@ -85,22 +83,22 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function }); } function parsePairKeyValue(entry) { - var valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR); + const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR); if (valueProps.length <= 0) return; - var keyPairPart = valueProps.shift(); + const keyPairPart = valueProps.shift(); if (!keyPairPart) return; - var separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR); + const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR); if (separatorIndex <= 0) return; - var key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim()); - var value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim()); - var metadata; + const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim()); + const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim()); + let metadata; if (valueProps.length > 0) { - metadata = index.src.baggageEntryMetadataFromString(valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)); + metadata = traceApi.baggageEntryMetadataFromString(valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)); } - return { key: key, value: value, metadata: metadata }; + return { key, value, metadata }; } /* @@ -124,39 +122,37 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Based on the Baggage specification: * https://w3c.github.io/baggage/ */ - var W3CBaggagePropagator = /** @class */ (function () { - function W3CBaggagePropagator() { - } - W3CBaggagePropagator.prototype.inject = function (context, carrier, setter) { - var baggage = index.src.propagation.getBaggage(context); + class W3CBaggagePropagator { + inject(context, carrier, setter) { + const baggage = traceApi.propagation.getBaggage(context); if (!baggage || isTracingSuppressed(context)) return; - var keyPairs = getKeyPairs(baggage) - .filter(function (pair) { + const keyPairs = getKeyPairs(baggage) + .filter((pair) => { return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; }) .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS); - var headerValue = serializeKeyPairs(keyPairs); + const headerValue = serializeKeyPairs(keyPairs); if (headerValue.length > 0) { setter.set(carrier, BAGGAGE_HEADER, headerValue); } - }; - W3CBaggagePropagator.prototype.extract = function (context, carrier, getter) { - var headerValue = getter.get(carrier, BAGGAGE_HEADER); - var baggageString = Array.isArray(headerValue) + } + extract(context, carrier, getter) { + const headerValue = getter.get(carrier, BAGGAGE_HEADER); + const baggageString = Array.isArray(headerValue) ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR) : headerValue; if (!baggageString) return context; - var baggage = {}; + const baggage = {}; if (baggageString.length === 0) { return context; } - var pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR); - pairs.forEach(function (entry) { - var keyPair = parsePairKeyValue(entry); + const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR); + pairs.forEach(entry => { + const keyPair = parsePairKeyValue(entry); if (keyPair) { - var baggageEntry = { value: keyPair.value }; + const baggageEntry = { value: keyPair.value }; if (keyPair.metadata) { baggageEntry.metadata = keyPair.metadata; } @@ -166,13 +162,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function if (Object.entries(baggage).length === 0) { return context; } - return index.src.propagation.setBaggage(context, index.src.propagation.createBaggage(baggage)); - }; - W3CBaggagePropagator.prototype.fields = function () { + return traceApi.propagation.setBaggage(context, traceApi.propagation.createBaggage(baggage)); + } + fields() { return [BAGGAGE_HEADER]; - }; - return W3CBaggagePropagator; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -189,64 +184,26 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __values$4 = (this && this.__values) || function(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."); - }; - var __read$5 = (this && this.__read) || function (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 sanitizeAttributes(attributes) { - var e_1, _a; - var out = {}; + const out = {}; if (typeof attributes !== 'object' || attributes == null) { return out; } - try { - for (var _b = __values$4(Object.entries(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) { - var _d = __read$5(_c.value, 2), key = _d[0], val = _d[1]; - if (!isAttributeKey(key)) { - index.src.diag.warn("Invalid attribute key: " + key); - continue; - } - if (!isAttributeValue(val)) { - index.src.diag.warn("Invalid attribute value set for key: " + key); - continue; - } - if (Array.isArray(val)) { - out[key] = val.slice(); - } - else { - out[key] = val; - } + for (const [key, val] of Object.entries(attributes)) { + if (!isAttributeKey(key)) { + traceApi.diag.warn(`Invalid attribute key: ${key}`); + continue; } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + if (!isAttributeValue(val)) { + traceApi.diag.warn(`Invalid attribute value set for key: ${key}`); + continue; + } + if (Array.isArray(val)) { + out[key] = val.slice(); + } + else { + out[key] = val; } - finally { if (e_1) throw e_1.error; } } return out; } @@ -263,34 +220,23 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return isValidPrimitiveAttributeValue(val); } function isHomogeneousAttributeValueArray(arr) { - var e_2, _a; - var type; - try { - for (var arr_1 = __values$4(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) { - var element = arr_1_1.value; - // null/undefined elements are allowed - if (element == null) - continue; - if (!type) { - if (isValidPrimitiveAttributeValue(element)) { - type = typeof element; - continue; - } - // encountered an invalid primitive - return false; - } - if (typeof element === type) { + let type; + for (const element of arr) { + // null/undefined elements are allowed + if (element == null) + continue; + if (!type) { + if (isValidPrimitiveAttributeValue(element)) { + type = typeof element; continue; } + // encountered an invalid primitive return false; } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1); + if (typeof element === type) { + continue; } - finally { if (e_2) throw e_2.error; } + return false; } return true; } @@ -324,8 +270,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * console logger if one was not provided. */ function loggingErrorHandler() { - return function (ex) { - index.src.diag.error(stringifyException(ex)); + return (ex) => { + traceApi.diag.error(stringifyException(ex)); }; } /** @@ -346,13 +292,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * the first insert wins. */ function flattenException(ex) { - var result = {}; - var current = ex; + const result = {}; + let current = ex; while (current !== null) { - Object.getOwnPropertyNames(current).forEach(function (propertyName) { + Object.getOwnPropertyNames(current).forEach(propertyName => { if (result[propertyName]) return; - var value = current[propertyName]; + const value = current[propertyName]; if (value) { result[propertyName] = String(value); } @@ -378,7 +324,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ /** The global error handler delegate */ - var delegateHandler = loggingErrorHandler(); + let delegateHandler = loggingErrorHandler(); /** * Return the global error handler * @param {Exception} ex @@ -415,24 +361,24 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function TracesSamplerValues["TraceIdRatio"] = "traceidratio"; })(TracesSamplerValues || (TracesSamplerValues = {})); - var DEFAULT_LIST_SEPARATOR = ","; - var ENVIRONMENT_BOOLEAN_KEYS = ["OTEL_SDK_DISABLED"]; + const DEFAULT_LIST_SEPARATOR = ","; + const ENVIRONMENT_BOOLEAN_KEYS = ["OTEL_SDK_DISABLED"]; function isEnvVarABoolean(key) { return ENVIRONMENT_BOOLEAN_KEYS.indexOf(key) > -1; } - var ENVIRONMENT_NUMBERS_KEYS = ["OTEL_BSP_EXPORT_TIMEOUT", "OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "OTEL_BSP_MAX_QUEUE_SIZE", "OTEL_BSP_SCHEDULE_DELAY", "OTEL_BLRP_EXPORT_TIMEOUT", "OTEL_BLRP_MAX_EXPORT_BATCH_SIZE", "OTEL_BLRP_MAX_QUEUE_SIZE", "OTEL_BLRP_SCHEDULE_DELAY", "OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", "OTEL_ATTRIBUTE_COUNT_LIMIT", "OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT", "OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT", "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT", "OTEL_SPAN_EVENT_COUNT_LIMIT", "OTEL_SPAN_LINK_COUNT_LIMIT", "OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT", "OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT", "OTEL_EXPORTER_OTLP_TIMEOUT", "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "OTEL_EXPORTER_OTLP_METRICS_TIMEOUT", "OTEL_EXPORTER_OTLP_LOGS_TIMEOUT", "OTEL_EXPORTER_JAEGER_AGENT_PORT"]; + const ENVIRONMENT_NUMBERS_KEYS = ["OTEL_BSP_EXPORT_TIMEOUT", "OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "OTEL_BSP_MAX_QUEUE_SIZE", "OTEL_BSP_SCHEDULE_DELAY", "OTEL_BLRP_EXPORT_TIMEOUT", "OTEL_BLRP_MAX_EXPORT_BATCH_SIZE", "OTEL_BLRP_MAX_QUEUE_SIZE", "OTEL_BLRP_SCHEDULE_DELAY", "OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", "OTEL_ATTRIBUTE_COUNT_LIMIT", "OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT", "OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT", "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT", "OTEL_SPAN_EVENT_COUNT_LIMIT", "OTEL_SPAN_LINK_COUNT_LIMIT", "OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT", "OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT", "OTEL_EXPORTER_OTLP_TIMEOUT", "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "OTEL_EXPORTER_OTLP_METRICS_TIMEOUT", "OTEL_EXPORTER_OTLP_LOGS_TIMEOUT", "OTEL_EXPORTER_JAEGER_AGENT_PORT"]; function isEnvVarANumber(key) { return ENVIRONMENT_NUMBERS_KEYS.indexOf(key) > -1; } - var ENVIRONMENT_LISTS_KEYS = ["OTEL_NO_PATCH_MODULES", "OTEL_PROPAGATORS", "OTEL_SEMCONV_STABILITY_OPT_IN"]; + const ENVIRONMENT_LISTS_KEYS = ["OTEL_NO_PATCH_MODULES", "OTEL_PROPAGATORS", "OTEL_SEMCONV_STABILITY_OPT_IN"]; function isEnvVarAList(key) { return ENVIRONMENT_LISTS_KEYS.indexOf(key) > -1; } - var DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; - var DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; - var DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128; - var DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128; - var DEFAULT_ENVIRONMENT = { + const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; + const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; + const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128; + const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128; + const DEFAULT_ENVIRONMENT = { OTEL_SDK_DISABLED: false, CONTAINER_NAME: "", ECS_CONTAINER_METADATA_URI_V4: "", @@ -466,7 +412,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000, OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000, OTEL_EXPORTER_ZIPKIN_ENDPOINT: "http://localhost:9411/api/v2/spans", - OTEL_LOG_LEVEL: index.src.DiagLogLevel.INFO, + OTEL_LOG_LEVEL: traceApi.DiagLogLevel.INFO, OTEL_NO_PATCH_MODULES: [], OTEL_PROPAGATORS: ["tracecontext", "baggage"], OTEL_RESOURCE_ATTRIBUTES: "", @@ -516,18 +462,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function if (typeof values[key] === "undefined") { return; } - var value = String(values[key]); + const value = String(values[key]); environment[key] = value.toLowerCase() === "true"; } - function parseNumber(name, environment, values, min, max) { - if (min === void 0) { - min = -Infinity; - } - if (max === void 0) { - max = Infinity; - } + function parseNumber(name, environment, values, min = -Infinity, max = Infinity) { if (typeof values[name] !== "undefined") { - var value = Number(values[name]); + const value = Number(values[name]); if (!isNaN(value)) { if (value < min) { environment[name] = min; @@ -539,39 +479,34 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } } } - function parseStringList(name, output, input, separator) { - if (separator === void 0) { - separator = DEFAULT_LIST_SEPARATOR; - } - var givenValue = input[name]; + function parseStringList(name, output, input, separator = DEFAULT_LIST_SEPARATOR) { + const givenValue = input[name]; if (typeof givenValue === "string") { - output[name] = givenValue.split(separator).map(function (v) { - return v.trim(); - }); + output[name] = givenValue.split(separator).map(v => v.trim()); } } - var logLevelMap = { - ALL: index.src.DiagLogLevel.ALL, - VERBOSE: index.src.DiagLogLevel.VERBOSE, - DEBUG: index.src.DiagLogLevel.DEBUG, - INFO: index.src.DiagLogLevel.INFO, - WARN: index.src.DiagLogLevel.WARN, - ERROR: index.src.DiagLogLevel.ERROR, - NONE: index.src.DiagLogLevel.NONE + const logLevelMap = { + ALL: traceApi.DiagLogLevel.ALL, + VERBOSE: traceApi.DiagLogLevel.VERBOSE, + DEBUG: traceApi.DiagLogLevel.DEBUG, + INFO: traceApi.DiagLogLevel.INFO, + WARN: traceApi.DiagLogLevel.WARN, + ERROR: traceApi.DiagLogLevel.ERROR, + NONE: traceApi.DiagLogLevel.NONE }; function setLogLevelFromEnv(key, environment, values) { - var value = values[key]; + const value = values[key]; if (typeof value === "string") { - var theLevel = logLevelMap[value.toUpperCase()]; + const theLevel = logLevelMap[value.toUpperCase()]; if (theLevel != null) { environment[key] = theLevel; } } } function parseEnvironment(values) { - var environment = {}; - for (var env in DEFAULT_ENVIRONMENT) { - var key = env; + const environment = {}; + for (const env in DEFAULT_ENVIRONMENT) { + const key = env; switch (key) { case "OTEL_LOG_LEVEL": setLogLevelFromEnv(key, environment, values); @@ -584,7 +519,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } else if (isEnvVarAList(key)) { parseStringList(key, environment, values); } else { - var value = values[key]; + const value = values[key]; if (typeof value !== "undefined" && value !== null) { environment[key] = String(value); } @@ -594,10 +529,6 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return environment; } - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - /* * Copyright The OpenTelemetry Authors * @@ -623,14 +554,14 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function */ /** only globals that common to node and browsers are allowed */ // eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef - var _globalThis = typeof globalThis === 'object' + const _globalThis = typeof globalThis === 'object' ? globalThis : typeof self === 'object' ? self : typeof window === 'object' ? window - : typeof global$1 === 'object' - ? global$1 + : typeof traceApi.global === 'object' + ? traceApi.global : {}; /* @@ -652,54 +583,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Gets the environment variables */ function getEnv() { - var globalEnv = parseEnvironment(_globalThis); + const globalEnv = parseEnvironment(_globalThis); return Object.assign({}, DEFAULT_ENVIRONMENT, globalEnv); } function getEnvWithoutDefaults() { return parseEnvironment(_globalThis); } - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - (this && this.__read) || function (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; - }; - (this && this.__spreadArray) || function (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)); - }; - Array(32); /* @@ -717,7 +607,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var otperformance = performance; + const otperformance = performance; /* * Copyright The OpenTelemetry Authors @@ -735,52 +625,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ // this is autogenerated file, see scripts/version-update.js - var VERSION$1 = '1.27.0'; - - var src = {}; - - var trace = {}; - - var SemanticAttributes = {}; - - var utils = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(utils, "__esModule", { value: true }); - utils.createConstMap = void 0; - /** - * Creates a const map from the given values - * @param values - An array of values to be used as keys and values in the map. - * @returns A populated version of the map with the values and keys derived from the values. - */ - /*#__NO_SIDE_EFFECTS__*/ - function createConstMap(values) { - // eslint-disable-next-line prefer-const, @typescript-eslint/no-explicit-any - let res = {}; - const len = values.length; - for (let lp = 0; lp < len; lp++) { - const val = values[lp]; - if (val) { - res[String(val).toUpperCase().replace(/[-.]/g, '_')] = val; - } - } - return res; - } - utils.createConstMap = createConstMap; + const VERSION$1 = '1.27.0'; /* * Copyright The OpenTelemetry Authors @@ -797,4795 +642,194 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - Object.defineProperty(SemanticAttributes, "__esModule", { value: true }); - SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_ICC = SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MNC = SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MCC = SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_NAME = SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_TYPE = SemanticAttributes.SEMATTRS_NET_HOST_NAME = SemanticAttributes.SEMATTRS_NET_HOST_PORT = SemanticAttributes.SEMATTRS_NET_HOST_IP = SemanticAttributes.SEMATTRS_NET_PEER_NAME = SemanticAttributes.SEMATTRS_NET_PEER_PORT = SemanticAttributes.SEMATTRS_NET_PEER_IP = SemanticAttributes.SEMATTRS_NET_TRANSPORT = SemanticAttributes.SEMATTRS_FAAS_INVOKED_REGION = SemanticAttributes.SEMATTRS_FAAS_INVOKED_PROVIDER = SemanticAttributes.SEMATTRS_FAAS_INVOKED_NAME = SemanticAttributes.SEMATTRS_FAAS_COLDSTART = SemanticAttributes.SEMATTRS_FAAS_CRON = SemanticAttributes.SEMATTRS_FAAS_TIME = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_NAME = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_TIME = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_OPERATION = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_COLLECTION = SemanticAttributes.SEMATTRS_FAAS_EXECUTION = SemanticAttributes.SEMATTRS_FAAS_TRIGGER = SemanticAttributes.SEMATTRS_EXCEPTION_ESCAPED = SemanticAttributes.SEMATTRS_EXCEPTION_STACKTRACE = SemanticAttributes.SEMATTRS_EXCEPTION_MESSAGE = SemanticAttributes.SEMATTRS_EXCEPTION_TYPE = SemanticAttributes.SEMATTRS_DB_SQL_TABLE = SemanticAttributes.SEMATTRS_DB_MONGODB_COLLECTION = SemanticAttributes.SEMATTRS_DB_REDIS_DATABASE_INDEX = SemanticAttributes.SEMATTRS_DB_HBASE_NAMESPACE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = SemanticAttributes.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = SemanticAttributes.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_TABLE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = SemanticAttributes.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_KEYSPACE = SemanticAttributes.SEMATTRS_DB_MSSQL_INSTANCE_NAME = SemanticAttributes.SEMATTRS_DB_OPERATION = SemanticAttributes.SEMATTRS_DB_STATEMENT = SemanticAttributes.SEMATTRS_DB_NAME = SemanticAttributes.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = SemanticAttributes.SEMATTRS_DB_USER = SemanticAttributes.SEMATTRS_DB_CONNECTION_STRING = SemanticAttributes.SEMATTRS_DB_SYSTEM = SemanticAttributes.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; - SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION_KIND = SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION = SemanticAttributes.SEMATTRS_MESSAGING_SYSTEM = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_COUNT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SEGMENT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SELECT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LIMIT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROJECTION = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = SemanticAttributes.SEMATTRS_HTTP_CLIENT_IP = SemanticAttributes.SEMATTRS_HTTP_ROUTE = SemanticAttributes.SEMATTRS_HTTP_SERVER_NAME = SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = SemanticAttributes.SEMATTRS_HTTP_USER_AGENT = SemanticAttributes.SEMATTRS_HTTP_FLAVOR = SemanticAttributes.SEMATTRS_HTTP_STATUS_CODE = SemanticAttributes.SEMATTRS_HTTP_SCHEME = SemanticAttributes.SEMATTRS_HTTP_HOST = SemanticAttributes.SEMATTRS_HTTP_TARGET = SemanticAttributes.SEMATTRS_HTTP_URL = SemanticAttributes.SEMATTRS_HTTP_METHOD = SemanticAttributes.SEMATTRS_CODE_LINENO = SemanticAttributes.SEMATTRS_CODE_FILEPATH = SemanticAttributes.SEMATTRS_CODE_NAMESPACE = SemanticAttributes.SEMATTRS_CODE_FUNCTION = SemanticAttributes.SEMATTRS_THREAD_NAME = SemanticAttributes.SEMATTRS_THREAD_ID = SemanticAttributes.SEMATTRS_ENDUSER_SCOPE = SemanticAttributes.SEMATTRS_ENDUSER_ROLE = SemanticAttributes.SEMATTRS_ENDUSER_ID = SemanticAttributes.SEMATTRS_PEER_SERVICE = void 0; - SemanticAttributes.DBSYSTEMVALUES_FILEMAKER = SemanticAttributes.DBSYSTEMVALUES_DERBY = SemanticAttributes.DBSYSTEMVALUES_FIREBIRD = SemanticAttributes.DBSYSTEMVALUES_ADABAS = SemanticAttributes.DBSYSTEMVALUES_CACHE = SemanticAttributes.DBSYSTEMVALUES_EDB = SemanticAttributes.DBSYSTEMVALUES_FIRSTSQL = SemanticAttributes.DBSYSTEMVALUES_INGRES = SemanticAttributes.DBSYSTEMVALUES_HANADB = SemanticAttributes.DBSYSTEMVALUES_MAXDB = SemanticAttributes.DBSYSTEMVALUES_PROGRESS = SemanticAttributes.DBSYSTEMVALUES_HSQLDB = SemanticAttributes.DBSYSTEMVALUES_CLOUDSCAPE = SemanticAttributes.DBSYSTEMVALUES_HIVE = SemanticAttributes.DBSYSTEMVALUES_REDSHIFT = SemanticAttributes.DBSYSTEMVALUES_POSTGRESQL = SemanticAttributes.DBSYSTEMVALUES_DB2 = SemanticAttributes.DBSYSTEMVALUES_ORACLE = SemanticAttributes.DBSYSTEMVALUES_MYSQL = SemanticAttributes.DBSYSTEMVALUES_MSSQL = SemanticAttributes.DBSYSTEMVALUES_OTHER_SQL = SemanticAttributes.SemanticAttributes = SemanticAttributes.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = SemanticAttributes.SEMATTRS_MESSAGE_COMPRESSED_SIZE = SemanticAttributes.SEMATTRS_MESSAGE_ID = SemanticAttributes.SEMATTRS_MESSAGE_TYPE = SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_CODE = SemanticAttributes.SEMATTRS_RPC_JSONRPC_REQUEST_ID = SemanticAttributes.SEMATTRS_RPC_JSONRPC_VERSION = SemanticAttributes.SEMATTRS_RPC_GRPC_STATUS_CODE = SemanticAttributes.SEMATTRS_RPC_METHOD = SemanticAttributes.SEMATTRS_RPC_SERVICE = SemanticAttributes.SEMATTRS_RPC_SYSTEM = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_PARTITION = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = SemanticAttributes.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = SemanticAttributes.SEMATTRS_MESSAGING_CONSUMER_ID = SemanticAttributes.SEMATTRS_MESSAGING_OPERATION = SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = SemanticAttributes.SEMATTRS_MESSAGING_CONVERSATION_ID = SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_ID = SemanticAttributes.SEMATTRS_MESSAGING_URL = SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL_VERSION = SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL = SemanticAttributes.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; - SemanticAttributes.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = SemanticAttributes.FaasDocumentOperationValues = SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_DELETE = SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_EDIT = SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_INSERT = SemanticAttributes.FaasTriggerValues = SemanticAttributes.FAASTRIGGERVALUES_OTHER = SemanticAttributes.FAASTRIGGERVALUES_TIMER = SemanticAttributes.FAASTRIGGERVALUES_PUBSUB = SemanticAttributes.FAASTRIGGERVALUES_HTTP = SemanticAttributes.FAASTRIGGERVALUES_DATASOURCE = SemanticAttributes.DbCassandraConsistencyLevelValues = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = SemanticAttributes.DbSystemValues = SemanticAttributes.DBSYSTEMVALUES_COCKROACHDB = SemanticAttributes.DBSYSTEMVALUES_MEMCACHED = SemanticAttributes.DBSYSTEMVALUES_ELASTICSEARCH = SemanticAttributes.DBSYSTEMVALUES_GEODE = SemanticAttributes.DBSYSTEMVALUES_NEO4J = SemanticAttributes.DBSYSTEMVALUES_DYNAMODB = SemanticAttributes.DBSYSTEMVALUES_COSMOSDB = SemanticAttributes.DBSYSTEMVALUES_COUCHDB = SemanticAttributes.DBSYSTEMVALUES_COUCHBASE = SemanticAttributes.DBSYSTEMVALUES_REDIS = SemanticAttributes.DBSYSTEMVALUES_MONGODB = SemanticAttributes.DBSYSTEMVALUES_HBASE = SemanticAttributes.DBSYSTEMVALUES_CASSANDRA = SemanticAttributes.DBSYSTEMVALUES_COLDFUSION = SemanticAttributes.DBSYSTEMVALUES_H2 = SemanticAttributes.DBSYSTEMVALUES_VERTICA = SemanticAttributes.DBSYSTEMVALUES_TERADATA = SemanticAttributes.DBSYSTEMVALUES_SYBASE = SemanticAttributes.DBSYSTEMVALUES_SQLITE = SemanticAttributes.DBSYSTEMVALUES_POINTBASE = SemanticAttributes.DBSYSTEMVALUES_PERVASIVE = SemanticAttributes.DBSYSTEMVALUES_NETEZZA = SemanticAttributes.DBSYSTEMVALUES_MARIADB = SemanticAttributes.DBSYSTEMVALUES_INTERBASE = SemanticAttributes.DBSYSTEMVALUES_INSTANTDB = SemanticAttributes.DBSYSTEMVALUES_INFORMIX = void 0; - SemanticAttributes.MESSAGINGOPERATIONVALUES_RECEIVE = SemanticAttributes.MessagingDestinationKindValues = SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_TOPIC = SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_QUEUE = SemanticAttributes.HttpFlavorValues = SemanticAttributes.HTTPFLAVORVALUES_QUIC = SemanticAttributes.HTTPFLAVORVALUES_SPDY = SemanticAttributes.HTTPFLAVORVALUES_HTTP_2_0 = SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_1 = SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_0 = SemanticAttributes.NetHostConnectionSubtypeValues = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NR = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = SemanticAttributes.NetHostConnectionTypeValues = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_CELL = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIRED = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIFI = SemanticAttributes.NetTransportValues = SemanticAttributes.NETTRANSPORTVALUES_OTHER = SemanticAttributes.NETTRANSPORTVALUES_INPROC = SemanticAttributes.NETTRANSPORTVALUES_PIPE = SemanticAttributes.NETTRANSPORTVALUES_UNIX = SemanticAttributes.NETTRANSPORTVALUES_IP = SemanticAttributes.NETTRANSPORTVALUES_IP_UDP = SemanticAttributes.NETTRANSPORTVALUES_IP_TCP = SemanticAttributes.FaasInvokedProviderValues = SemanticAttributes.FAASINVOKEDPROVIDERVALUES_GCP = SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AZURE = SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AWS = void 0; - SemanticAttributes.MessageTypeValues = SemanticAttributes.MESSAGETYPEVALUES_RECEIVED = SemanticAttributes.MESSAGETYPEVALUES_SENT = SemanticAttributes.RpcGrpcStatusCodeValues = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INTERNAL = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ABORTED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNKNOWN = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_CANCELLED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OK = SemanticAttributes.MessagingOperationValues = SemanticAttributes.MESSAGINGOPERATIONVALUES_PROCESS = void 0; - const utils_1$1 = utils; - //---------------------------------------------------------------------------------------------------------- - // DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2 - //---------------------------------------------------------------------------------------------------------- - //---------------------------------------------------------------------------------------------------------- - // Constant values for SemanticAttributes - //---------------------------------------------------------------------------------------------------------- - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_AWS_LAMBDA_INVOKED_ARN = 'aws.lambda.invoked_arn'; - const TMP_DB_SYSTEM = 'db.system'; - const TMP_DB_CONNECTION_STRING = 'db.connection_string'; - const TMP_DB_USER = 'db.user'; - const TMP_DB_JDBC_DRIVER_CLASSNAME = 'db.jdbc.driver_classname'; - const TMP_DB_NAME = 'db.name'; - const TMP_DB_STATEMENT = 'db.statement'; - const TMP_DB_OPERATION = 'db.operation'; - const TMP_DB_MSSQL_INSTANCE_NAME = 'db.mssql.instance_name'; - const TMP_DB_CASSANDRA_KEYSPACE = 'db.cassandra.keyspace'; - const TMP_DB_CASSANDRA_PAGE_SIZE = 'db.cassandra.page_size'; - const TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = 'db.cassandra.consistency_level'; - const TMP_DB_CASSANDRA_TABLE = 'db.cassandra.table'; - const TMP_DB_CASSANDRA_IDEMPOTENCE = 'db.cassandra.idempotence'; - const TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = 'db.cassandra.speculative_execution_count'; - const TMP_DB_CASSANDRA_COORDINATOR_ID = 'db.cassandra.coordinator.id'; - const TMP_DB_CASSANDRA_COORDINATOR_DC = 'db.cassandra.coordinator.dc'; - const TMP_DB_HBASE_NAMESPACE = 'db.hbase.namespace'; - const TMP_DB_REDIS_DATABASE_INDEX = 'db.redis.database_index'; - const TMP_DB_MONGODB_COLLECTION = 'db.mongodb.collection'; - const TMP_DB_SQL_TABLE = 'db.sql.table'; const TMP_EXCEPTION_TYPE = 'exception.type'; const TMP_EXCEPTION_MESSAGE = 'exception.message'; const TMP_EXCEPTION_STACKTRACE = 'exception.stacktrace'; - const TMP_EXCEPTION_ESCAPED = 'exception.escaped'; - const TMP_FAAS_TRIGGER = 'faas.trigger'; - const TMP_FAAS_EXECUTION = 'faas.execution'; - const TMP_FAAS_DOCUMENT_COLLECTION = 'faas.document.collection'; - const TMP_FAAS_DOCUMENT_OPERATION = 'faas.document.operation'; - const TMP_FAAS_DOCUMENT_TIME = 'faas.document.time'; - const TMP_FAAS_DOCUMENT_NAME = 'faas.document.name'; - const TMP_FAAS_TIME = 'faas.time'; - const TMP_FAAS_CRON = 'faas.cron'; - const TMP_FAAS_COLDSTART = 'faas.coldstart'; - const TMP_FAAS_INVOKED_NAME = 'faas.invoked_name'; - const TMP_FAAS_INVOKED_PROVIDER = 'faas.invoked_provider'; - const TMP_FAAS_INVOKED_REGION = 'faas.invoked_region'; - const TMP_NET_TRANSPORT = 'net.transport'; - const TMP_NET_PEER_IP = 'net.peer.ip'; - const TMP_NET_PEER_PORT = 'net.peer.port'; - const TMP_NET_PEER_NAME = 'net.peer.name'; - const TMP_NET_HOST_IP = 'net.host.ip'; - const TMP_NET_HOST_PORT = 'net.host.port'; - const TMP_NET_HOST_NAME = 'net.host.name'; - const TMP_NET_HOST_CONNECTION_TYPE = 'net.host.connection.type'; - const TMP_NET_HOST_CONNECTION_SUBTYPE = 'net.host.connection.subtype'; - const TMP_NET_HOST_CARRIER_NAME = 'net.host.carrier.name'; - const TMP_NET_HOST_CARRIER_MCC = 'net.host.carrier.mcc'; - const TMP_NET_HOST_CARRIER_MNC = 'net.host.carrier.mnc'; - const TMP_NET_HOST_CARRIER_ICC = 'net.host.carrier.icc'; - const TMP_PEER_SERVICE = 'peer.service'; - const TMP_ENDUSER_ID = 'enduser.id'; - const TMP_ENDUSER_ROLE = 'enduser.role'; - const TMP_ENDUSER_SCOPE = 'enduser.scope'; - const TMP_THREAD_ID = 'thread.id'; - const TMP_THREAD_NAME = 'thread.name'; - const TMP_CODE_FUNCTION = 'code.function'; - const TMP_CODE_NAMESPACE = 'code.namespace'; - const TMP_CODE_FILEPATH = 'code.filepath'; - const TMP_CODE_LINENO = 'code.lineno'; - const TMP_HTTP_METHOD = 'http.method'; - const TMP_HTTP_URL = 'http.url'; - const TMP_HTTP_TARGET = 'http.target'; - const TMP_HTTP_HOST = 'http.host'; - const TMP_HTTP_SCHEME = 'http.scheme'; - const TMP_HTTP_STATUS_CODE = 'http.status_code'; - const TMP_HTTP_FLAVOR = 'http.flavor'; - const TMP_HTTP_USER_AGENT = 'http.user_agent'; - const TMP_HTTP_REQUEST_CONTENT_LENGTH = 'http.request_content_length'; - const TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = 'http.request_content_length_uncompressed'; const TMP_HTTP_RESPONSE_CONTENT_LENGTH = 'http.response_content_length'; const TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = 'http.response_content_length_uncompressed'; - const TMP_HTTP_SERVER_NAME = 'http.server_name'; - const TMP_HTTP_ROUTE = 'http.route'; - const TMP_HTTP_CLIENT_IP = 'http.client_ip'; - const TMP_AWS_DYNAMODB_TABLE_NAMES = 'aws.dynamodb.table_names'; - const TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = 'aws.dynamodb.consumed_capacity'; - const TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = 'aws.dynamodb.item_collection_metrics'; - const TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = 'aws.dynamodb.provisioned_read_capacity'; - const TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = 'aws.dynamodb.provisioned_write_capacity'; - const TMP_AWS_DYNAMODB_CONSISTENT_READ = 'aws.dynamodb.consistent_read'; - const TMP_AWS_DYNAMODB_PROJECTION = 'aws.dynamodb.projection'; - const TMP_AWS_DYNAMODB_LIMIT = 'aws.dynamodb.limit'; - const TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = 'aws.dynamodb.attributes_to_get'; - const TMP_AWS_DYNAMODB_INDEX_NAME = 'aws.dynamodb.index_name'; - const TMP_AWS_DYNAMODB_SELECT = 'aws.dynamodb.select'; - const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = 'aws.dynamodb.global_secondary_indexes'; - const TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = 'aws.dynamodb.local_secondary_indexes'; - const TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = 'aws.dynamodb.exclusive_start_table'; - const TMP_AWS_DYNAMODB_TABLE_COUNT = 'aws.dynamodb.table_count'; - const TMP_AWS_DYNAMODB_SCAN_FORWARD = 'aws.dynamodb.scan_forward'; - const TMP_AWS_DYNAMODB_SEGMENT = 'aws.dynamodb.segment'; - const TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = 'aws.dynamodb.total_segments'; - const TMP_AWS_DYNAMODB_COUNT = 'aws.dynamodb.count'; - const TMP_AWS_DYNAMODB_SCANNED_COUNT = 'aws.dynamodb.scanned_count'; - const TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = 'aws.dynamodb.attribute_definitions'; - const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = 'aws.dynamodb.global_secondary_index_updates'; - const TMP_MESSAGING_SYSTEM = 'messaging.system'; - const TMP_MESSAGING_DESTINATION = 'messaging.destination'; - const TMP_MESSAGING_DESTINATION_KIND = 'messaging.destination_kind'; - const TMP_MESSAGING_TEMP_DESTINATION = 'messaging.temp_destination'; - const TMP_MESSAGING_PROTOCOL = 'messaging.protocol'; - const TMP_MESSAGING_PROTOCOL_VERSION = 'messaging.protocol_version'; - const TMP_MESSAGING_URL = 'messaging.url'; - const TMP_MESSAGING_MESSAGE_ID = 'messaging.message_id'; - const TMP_MESSAGING_CONVERSATION_ID = 'messaging.conversation_id'; - const TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = 'messaging.message_payload_size_bytes'; - const TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = 'messaging.message_payload_compressed_size_bytes'; - const TMP_MESSAGING_OPERATION = 'messaging.operation'; - const TMP_MESSAGING_CONSUMER_ID = 'messaging.consumer_id'; - const TMP_MESSAGING_RABBITMQ_ROUTING_KEY = 'messaging.rabbitmq.routing_key'; - const TMP_MESSAGING_KAFKA_MESSAGE_KEY = 'messaging.kafka.message_key'; - const TMP_MESSAGING_KAFKA_CONSUMER_GROUP = 'messaging.kafka.consumer_group'; - const TMP_MESSAGING_KAFKA_CLIENT_ID = 'messaging.kafka.client_id'; - const TMP_MESSAGING_KAFKA_PARTITION = 'messaging.kafka.partition'; - const TMP_MESSAGING_KAFKA_TOMBSTONE = 'messaging.kafka.tombstone'; - const TMP_RPC_SYSTEM = 'rpc.system'; - const TMP_RPC_SERVICE = 'rpc.service'; - const TMP_RPC_METHOD = 'rpc.method'; - const TMP_RPC_GRPC_STATUS_CODE = 'rpc.grpc.status_code'; - const TMP_RPC_JSONRPC_VERSION = 'rpc.jsonrpc.version'; - const TMP_RPC_JSONRPC_REQUEST_ID = 'rpc.jsonrpc.request_id'; - const TMP_RPC_JSONRPC_ERROR_CODE = 'rpc.jsonrpc.error_code'; - const TMP_RPC_JSONRPC_ERROR_MESSAGE = 'rpc.jsonrpc.error_message'; - const TMP_MESSAGE_TYPE = 'message.type'; - const TMP_MESSAGE_ID = 'message.id'; - const TMP_MESSAGE_COMPRESSED_SIZE = 'message.compressed_size'; - const TMP_MESSAGE_UNCOMPRESSED_SIZE = 'message.uncompressed_size'; /** - * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable). - * - * Note: This may be different from `faas.id` if an alias is involved. - * - * @deprecated use ATTR_AWS_LAMBDA_INVOKED_ARN - */ - SemanticAttributes.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated use ATTR_DB_SYSTEM - */ - SemanticAttributes.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; - /** - * The connection string used to connect to the database. It is recommended to remove embedded credentials. - * - * @deprecated use ATTR_DB_CONNECTION_STRING - */ - SemanticAttributes.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; - /** - * Username for accessing the database. + * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. * - * @deprecated use ATTR_DB_USER + * @deprecated use ATTR_EXCEPTION_TYPE */ - SemanticAttributes.SEMATTRS_DB_USER = TMP_DB_USER; + const SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; /** - * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect. + * The exception message. * - * @deprecated use ATTR_DB_JDBC_DRIVER_CLASSNAME + * @deprecated use ATTR_EXCEPTION_MESSAGE */ - SemanticAttributes.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + const SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; /** - * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). - * - * Note: In some SQL databases, the database name to be used is called "schema name". + * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. * - * @deprecated use ATTR_DB_NAME + * @deprecated use ATTR_EXCEPTION_STACKTRACE */ - SemanticAttributes.SEMATTRS_DB_NAME = TMP_DB_NAME; + const SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; /** - * The database statement being executed. - * - * Note: The value may be sanitized to exclude sensitive information. + * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. * - * @deprecated use ATTR_DB_STATEMENT + * @deprecated use ATTR_HTTP_RESPONSE_CONTENT_LENGTH */ - SemanticAttributes.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + const SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; /** - * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword. - * - * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. + * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. * - * @deprecated use ATTR_DB_OPERATION + * @deprecated use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED */ - SemanticAttributes.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; - /** - * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance. - * - * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). + const SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; + + /* + * Copyright The OpenTelemetry Authors * - * @deprecated use ATTR_DB_MSSQL_INSTANCE_NAME - */ - SemanticAttributes.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; - /** - * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. + * 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 * - * @deprecated use ATTR_DB_CASSANDRA_KEYSPACE - */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; - /** - * The fetch size used for paging, i.e. how many rows will be returned at once. + * https://www.apache.org/licenses/LICENSE-2.0 * - * @deprecated use ATTR_DB_CASSANDRA_PAGE_SIZE + * 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. */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + const TMP_PROCESS_RUNTIME_NAME = 'process.runtime.name'; + const TMP_SERVICE_NAME = 'service.name'; + const TMP_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; + const TMP_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; + const TMP_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. * - * @deprecated use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL + * @deprecated use ATTR_PROCESS_RUNTIME_NAME */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + const SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; /** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + * Logical name of the service. * - * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. + * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. * - * @deprecated use ATTR_DB_CASSANDRA_TABLE + * @deprecated use ATTR_SERVICE_NAME */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + const SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; /** - * Whether or not the query is idempotent. + * The name of the telemetry SDK as defined above. * - * @deprecated use ATTR_DB_CASSANDRA_IDEMPOTENCE + * @deprecated use ATTR_TELEMETRY_SDK_NAME */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + const SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; /** - * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. + * The language of the telemetry SDK. * - * @deprecated use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT + * @deprecated use ATTR_TELEMETRY_SDK_LANGUAGE */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + const SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; /** - * The ID of the coordinating node for a query. + * The version string of the telemetry SDK. * - * @deprecated use ATTR_DB_CASSANDRA_COORDINATOR_ID + * @deprecated use ATTR_TELEMETRY_SDK_VERSION */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + const SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; + const TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = 'webjs'; /** - * The data center of the coordinating node for a query. + * The language of the telemetry SDK. * - * @deprecated use ATTR_DB_CASSANDRA_COORDINATOR_DC + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. */ - SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; - /** - * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute. + const TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; + + /* + * Copyright The OpenTelemetry Authors * - * @deprecated use ATTR_DB_HBASE_NAMESPACE - */ - SemanticAttributes.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; - /** - * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute. + * 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 * - * @deprecated use ATTR_DB_REDIS_DATABASE_INDEX - */ - SemanticAttributes.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; - /** - * The collection being accessed within the database stated in `db.name`. + * https://www.apache.org/licenses/LICENSE-2.0 * - * @deprecated use ATTR_DB_MONGODB_COLLECTION + * 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. */ - SemanticAttributes.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; - /** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + /** Constants describing the SDK in use */ + const SDK_INFO = { + [SEMRESATTRS_TELEMETRY_SDK_NAME]: 'opentelemetry', + [SEMRESATTRS_PROCESS_RUNTIME_NAME]: 'browser', + [SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]: TELEMETRYSDKLANGUAGEVALUES_WEBJS, + [SEMRESATTRS_TELEMETRY_SDK_VERSION]: VERSION$1, + }; + + /* + * Copyright The OpenTelemetry Authors * - * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. + * 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 * - * @deprecated use ATTR_DB_SQL_TABLE - */ - SemanticAttributes.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. + * https://www.apache.org/licenses/LICENSE-2.0 * - * @deprecated use ATTR_EXCEPTION_TYPE + * 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. */ - SemanticAttributes.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; - /** - * The exception message. + function unrefTimer(_timer) { } + + /* + * Copyright The OpenTelemetry Authors * - * @deprecated use ATTR_EXCEPTION_MESSAGE - */ - SemanticAttributes.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. + * 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 * - * @deprecated use ATTR_EXCEPTION_STACKTRACE - */ - SemanticAttributes.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; - /** - * SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. - * - * Note: An exception is considered to have escaped (or left) the scope of a span, - if that span is ended while the exception is still logically "in flight". - This may be actually "in flight" in some languages (e.g. if the exception - is passed to a Context manager's `__exit__` method in Python) but will - usually be caught at the point of recording the exception in most languages. - - It is usually not possible to determine at the point where an exception is thrown - whether it will escape the scope of a span. - However, it is trivial to know that an exception - will escape, if one checks for an active exception just before ending the span, - as done in the [example above](#exception-end-example). - - It follows that an exception may still escape the scope of the span - even if the `exception.escaped` attribute was not set or set to false, - since the event might have been recorded at a time where it was not - clear whether the exception will escape. - * - * @deprecated use ATTR_EXCEPTION_ESCAPED - */ - SemanticAttributes.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; - /** - * Type of the trigger on which the function is executed. + * https://www.apache.org/licenses/LICENSE-2.0 * - * @deprecated use ATTR_FAAS_TRIGGER + * 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. */ - SemanticAttributes.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + const NANOSECOND_DIGITS = 9; + const NANOSECOND_DIGITS_IN_MILLIS = 6; + const MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS); + const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); /** - * The execution ID of the current function execution. - * - * @deprecated use ATTR_FAAS_EXECUTION + * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]). + * @param epochMillis */ - SemanticAttributes.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + function millisToHrTime(epochMillis) { + const epochSeconds = epochMillis / 1000; + // Decimals only. + const seconds = Math.trunc(epochSeconds); + // Round sub-nanosecond accuracy to nanosecond. + const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS); + return [seconds, nanos]; + } + function getTimeOrigin() { + let timeOrigin = otperformance.timeOrigin; + if (typeof timeOrigin !== 'number') { + const perf = otperformance; + timeOrigin = perf.timing && perf.timing.fetchStart; + } + return timeOrigin; + } /** - * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. - * - * @deprecated use ATTR_FAAS_DOCUMENT_COLLECTION + * Returns an hrtime calculated via performance component. + * @param performanceNow */ - SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + function hrTime(performanceNow) { + const timeOrigin = millisToHrTime(getTimeOrigin()); + const now = millisToHrTime(typeof performanceNow === 'number' ? performanceNow : otperformance.now()); + return addHrTimes(timeOrigin, now); + } /** - * Describes the type of the operation that was performed on the data. * - * @deprecated use ATTR_FAAS_DOCUMENT_OPERATION - */ - SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; - /** - * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated use ATTR_FAAS_DOCUMENT_TIME - */ - SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; - /** - * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name. - * - * @deprecated use ATTR_FAAS_DOCUMENT_NAME - */ - SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; - /** - * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated use ATTR_FAAS_TIME - */ - SemanticAttributes.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; - /** - * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - * - * @deprecated use ATTR_FAAS_CRON - */ - SemanticAttributes.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; - /** - * A boolean that is true if the serverless function is executed for the first time (aka cold-start). - * - * @deprecated use ATTR_FAAS_COLDSTART - */ - SemanticAttributes.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; - /** - * The name of the invoked function. - * - * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function. - * - * @deprecated use ATTR_FAAS_INVOKED_NAME - */ - SemanticAttributes.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated use ATTR_FAAS_INVOKED_PROVIDER - */ - SemanticAttributes.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; - /** - * The cloud region of the invoked function. - * - * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function. - * - * @deprecated use ATTR_FAAS_INVOKED_REGION - */ - SemanticAttributes.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; - /** - * Transport protocol used. See note below. - * - * @deprecated use ATTR_NET_TRANSPORT - */ - SemanticAttributes.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; - /** - * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6). - * - * @deprecated use ATTR_NET_PEER_IP - */ - SemanticAttributes.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; - /** - * Remote port number. - * - * @deprecated use ATTR_NET_PEER_PORT - */ - SemanticAttributes.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; - /** - * Remote hostname or similar, see note below. - * - * @deprecated use ATTR_NET_PEER_NAME - */ - SemanticAttributes.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; - /** - * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host. - * - * @deprecated use ATTR_NET_HOST_IP - */ - SemanticAttributes.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; - /** - * Like `net.peer.port` but for the host port. - * - * @deprecated use ATTR_NET_HOST_PORT - */ - SemanticAttributes.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; - /** - * Local hostname or similar, see note below. - * - * @deprecated use ATTR_NET_HOST_NAME - */ - SemanticAttributes.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; - /** - * The internet connection type currently being used by the host. - * - * @deprecated use ATTR_NET_HOST_CONNECTION_TYPE - */ - SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated use ATTR_NET_HOST_CONNECTION_SUBTYPE - */ - SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; - /** - * The name of the mobile carrier. - * - * @deprecated use ATTR_NET_HOST_CARRIER_NAME - */ - SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; - /** - * The mobile carrier country code. - * - * @deprecated use ATTR_NET_HOST_CARRIER_MCC - */ - SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; - /** - * The mobile carrier network code. - * - * @deprecated use ATTR_NET_HOST_CARRIER_MNC - */ - SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; - /** - * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. - * - * @deprecated use ATTR_NET_HOST_CARRIER_ICC - */ - SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; - /** - * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any. - * - * @deprecated use ATTR_PEER_SERVICE - */ - SemanticAttributes.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; - /** - * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system. - * - * @deprecated use ATTR_ENDUSER_ID - */ - SemanticAttributes.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; - /** - * Actual/assumed role the client is making the request under extracted from token or application security context. - * - * @deprecated use ATTR_ENDUSER_ROLE - */ - SemanticAttributes.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; - /** - * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - * - * @deprecated use ATTR_ENDUSER_SCOPE - */ - SemanticAttributes.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; - /** - * Current "managed" thread ID (as opposed to OS thread ID). - * - * @deprecated use ATTR_THREAD_ID - */ - SemanticAttributes.SEMATTRS_THREAD_ID = TMP_THREAD_ID; - /** - * Current thread name. - * - * @deprecated use ATTR_THREAD_NAME - */ - SemanticAttributes.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; - /** - * The method or function name, or equivalent (usually rightmost part of the code unit's name). - * - * @deprecated use ATTR_CODE_FUNCTION - */ - SemanticAttributes.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; - /** - * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit. - * - * @deprecated use ATTR_CODE_NAMESPACE - */ - SemanticAttributes.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; - /** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). - * - * @deprecated use ATTR_CODE_FILEPATH - */ - SemanticAttributes.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; - /** - * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`. - * - * @deprecated use ATTR_CODE_LINENO - */ - SemanticAttributes.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; - /** - * HTTP request method. - * - * @deprecated use ATTR_HTTP_METHOD - */ - SemanticAttributes.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; - /** - * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. - * - * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`. - * - * @deprecated use ATTR_HTTP_URL - */ - SemanticAttributes.SEMATTRS_HTTP_URL = TMP_HTTP_URL; - /** - * The full request target as passed in a HTTP request line or equivalent. - * - * @deprecated use ATTR_HTTP_TARGET - */ - SemanticAttributes.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; - /** - * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note. - * - * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set. - * - * @deprecated use ATTR_HTTP_HOST - */ - SemanticAttributes.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; - /** - * The URI scheme identifying the used protocol. - * - * @deprecated use ATTR_HTTP_SCHEME - */ - SemanticAttributes.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; - /** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @deprecated use ATTR_HTTP_STATUS_CODE - */ - SemanticAttributes.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated use ATTR_HTTP_FLAVOR - */ - SemanticAttributes.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; - /** - * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client. - * - * @deprecated use ATTR_HTTP_USER_AGENT - */ - SemanticAttributes.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; - /** - * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated use ATTR_HTTP_REQUEST_CONTENT_LENGTH - */ - SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; - /** - * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED - */ - SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; - /** - * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated use ATTR_HTTP_RESPONSE_CONTENT_LENGTH - */ - SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; - /** - * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED - */ - SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; - /** - * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead). - * - * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available. - * - * @deprecated use ATTR_HTTP_SERVER_NAME - */ - SemanticAttributes.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; - /** - * The matched route (path template). - * - * @deprecated use ATTR_HTTP_ROUTE - */ - SemanticAttributes.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; - /** - * The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). - * - * Note: This is not necessarily the same as `net.peer.ip`, which would - identify the network-level peer, which may be a proxy. - - This attribute should be set when a source of information different - from the one used for `net.peer.ip`, is available even if that other - source just confirms the same value as `net.peer.ip`. - Rationale: For `net.peer.ip`, one typically does not know if it - comes from a proxy, reverse proxy, or the actual client. Setting - `http.client_ip` when it's the same as `net.peer.ip` means that - one is at least somewhat confident that the address is not that of - the closest proxy. - * - * @deprecated use ATTR_HTTP_CLIENT_IP - */ - SemanticAttributes.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; - /** - * The keys in the `RequestItems` object field. - * - * @deprecated use ATTR_AWS_DYNAMODB_TABLE_NAMES - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; - /** - * The JSON-serialized value of each item in the `ConsumedCapacity` response field. - * - * @deprecated use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; - /** - * The JSON-serialized value of the `ItemCollectionMetrics` response field. - * - * @deprecated use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; - /** - * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; - /** - * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; - /** - * The value of the `ConsistentRead` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_CONSISTENT_READ - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; - /** - * The value of the `ProjectionExpression` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_PROJECTION - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; - /** - * The value of the `Limit` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_LIMIT - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; - /** - * The value of the `AttributesToGet` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; - /** - * The value of the `IndexName` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_INDEX_NAME - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; - /** - * The value of the `Select` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_SELECT - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; - /** - * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field. - * - * @deprecated use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; - /** - * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field. - * - * @deprecated use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; - /** - * The value of the `ExclusiveStartTableName` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; - /** - * The the number of items in the `TableNames` response parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_TABLE_COUNT - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; - /** - * The value of the `ScanIndexForward` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_SCAN_FORWARD - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; - /** - * The value of the `Segment` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_SEGMENT - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; - /** - * The value of the `TotalSegments` request parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; - /** - * The value of the `Count` response parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_COUNT - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; - /** - * The value of the `ScannedCount` response parameter. - * - * @deprecated use ATTR_AWS_DYNAMODB_SCANNED_COUNT - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; - /** - * The JSON-serialized value of each item in the `AttributeDefinitions` request field. - * - * @deprecated use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; - /** - * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field. - * - * @deprecated use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES - */ - SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; - /** - * A string identifying the messaging system. - * - * @deprecated use ATTR_MESSAGING_SYSTEM - */ - SemanticAttributes.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; - /** - * The message destination name. This might be equal to the span name but is required nevertheless. - * - * @deprecated use ATTR_MESSAGING_DESTINATION - */ - SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; - /** - * The kind of message destination. - * - * @deprecated use ATTR_MESSAGING_DESTINATION_KIND - */ - SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; - /** - * A boolean that is true if the message destination is temporary. - * - * @deprecated use ATTR_MESSAGING_TEMP_DESTINATION - */ - SemanticAttributes.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; - /** - * The name of the transport protocol. - * - * @deprecated use ATTR_MESSAGING_PROTOCOL - */ - SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; - /** - * The version of the transport protocol. - * - * @deprecated use ATTR_MESSAGING_PROTOCOL_VERSION - */ - SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; - /** - * Connection string. - * - * @deprecated use ATTR_MESSAGING_URL - */ - SemanticAttributes.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; - /** - * A value used by the messaging system as an identifier for the message, represented as a string. - * - * @deprecated use ATTR_MESSAGING_MESSAGE_ID - */ - SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; - /** - * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". - * - * @deprecated use ATTR_MESSAGING_CONVERSATION_ID - */ - SemanticAttributes.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; - /** - * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported. - * - * @deprecated use ATTR_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES - */ - SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; - /** - * The compressed size of the message payload in bytes. - * - * @deprecated use ATTR_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES - */ - SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated use ATTR_MESSAGING_OPERATION - */ - SemanticAttributes.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; - /** - * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message. - * - * @deprecated use ATTR_MESSAGING_CONSUMER_ID - */ - SemanticAttributes.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; - /** - * RabbitMQ message routing key. - * - * @deprecated use ATTR_MESSAGING_RABBITMQ_ROUTING_KEY - */ - SemanticAttributes.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; - /** - * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. - * - * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value. - * - * @deprecated use ATTR_MESSAGING_KAFKA_MESSAGE_KEY - */ - SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; - /** - * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. - * - * @deprecated use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP - */ - SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; - /** - * Client Id for the Consumer or Producer that is handling the message. - * - * @deprecated use ATTR_MESSAGING_KAFKA_CLIENT_ID - */ - SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; - /** - * Partition the message is sent to. - * - * @deprecated use ATTR_MESSAGING_KAFKA_PARTITION - */ - SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; - /** - * A boolean that is true if the message is a tombstone. - * - * @deprecated use ATTR_MESSAGING_KAFKA_TOMBSTONE - */ - SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; - /** - * A string identifying the remoting system. - * - * @deprecated use ATTR_RPC_SYSTEM - */ - SemanticAttributes.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; - /** - * The full (logical) name of the service being called, including its package name, if applicable. - * - * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). - * - * @deprecated use ATTR_RPC_SERVICE - */ - SemanticAttributes.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; - /** - * The name of the (logical) method being called, must be equal to the $method part in the span name. - * - * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). - * - * @deprecated use ATTR_RPC_METHOD - */ - SemanticAttributes.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated use ATTR_RPC_GRPC_STATUS_CODE - */ - SemanticAttributes.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; - /** - * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted. - * - * @deprecated use ATTR_RPC_JSONRPC_VERSION - */ - SemanticAttributes.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; - /** - * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification. - * - * @deprecated use ATTR_RPC_JSONRPC_REQUEST_ID - */ - SemanticAttributes.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; - /** - * `error.code` property of response if it is an error response. - * - * @deprecated use ATTR_RPC_JSONRPC_ERROR_CODE - */ - SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; - /** - * `error.message` property of response if it is an error response. - * - * @deprecated use ATTR_RPC_JSONRPC_ERROR_MESSAGE - */ - SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; - /** - * Whether this is a received or sent message. - * - * @deprecated use ATTR_MESSAGE_TYPE - */ - SemanticAttributes.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; - /** - * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message. - * - * Note: This way we guarantee that the values will be consistent between different implementations. - * - * @deprecated use ATTR_MESSAGE_ID - */ - SemanticAttributes.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; - /** - * Compressed size of the message in bytes. - * - * @deprecated use ATTR_MESSAGE_COMPRESSED_SIZE - */ - SemanticAttributes.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; - /** - * Uncompressed size of the message in bytes. - * - * @deprecated use ATTR_MESSAGE_UNCOMPRESSED_SIZE - */ - SemanticAttributes.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; - /** - * Create exported Value Map for SemanticAttributes values - * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification - */ - SemanticAttributes.SemanticAttributes = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_AWS_LAMBDA_INVOKED_ARN, - TMP_DB_SYSTEM, - TMP_DB_CONNECTION_STRING, - TMP_DB_USER, - TMP_DB_JDBC_DRIVER_CLASSNAME, - TMP_DB_NAME, - TMP_DB_STATEMENT, - TMP_DB_OPERATION, - TMP_DB_MSSQL_INSTANCE_NAME, - TMP_DB_CASSANDRA_KEYSPACE, - TMP_DB_CASSANDRA_PAGE_SIZE, - TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, - TMP_DB_CASSANDRA_TABLE, - TMP_DB_CASSANDRA_IDEMPOTENCE, - TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, - TMP_DB_CASSANDRA_COORDINATOR_ID, - TMP_DB_CASSANDRA_COORDINATOR_DC, - TMP_DB_HBASE_NAMESPACE, - TMP_DB_REDIS_DATABASE_INDEX, - TMP_DB_MONGODB_COLLECTION, - TMP_DB_SQL_TABLE, - TMP_EXCEPTION_TYPE, - TMP_EXCEPTION_MESSAGE, - TMP_EXCEPTION_STACKTRACE, - TMP_EXCEPTION_ESCAPED, - TMP_FAAS_TRIGGER, - TMP_FAAS_EXECUTION, - TMP_FAAS_DOCUMENT_COLLECTION, - TMP_FAAS_DOCUMENT_OPERATION, - TMP_FAAS_DOCUMENT_TIME, - TMP_FAAS_DOCUMENT_NAME, - TMP_FAAS_TIME, - TMP_FAAS_CRON, - TMP_FAAS_COLDSTART, - TMP_FAAS_INVOKED_NAME, - TMP_FAAS_INVOKED_PROVIDER, - TMP_FAAS_INVOKED_REGION, - TMP_NET_TRANSPORT, - TMP_NET_PEER_IP, - TMP_NET_PEER_PORT, - TMP_NET_PEER_NAME, - TMP_NET_HOST_IP, - TMP_NET_HOST_PORT, - TMP_NET_HOST_NAME, - TMP_NET_HOST_CONNECTION_TYPE, - TMP_NET_HOST_CONNECTION_SUBTYPE, - TMP_NET_HOST_CARRIER_NAME, - TMP_NET_HOST_CARRIER_MCC, - TMP_NET_HOST_CARRIER_MNC, - TMP_NET_HOST_CARRIER_ICC, - TMP_PEER_SERVICE, - TMP_ENDUSER_ID, - TMP_ENDUSER_ROLE, - TMP_ENDUSER_SCOPE, - TMP_THREAD_ID, - TMP_THREAD_NAME, - TMP_CODE_FUNCTION, - TMP_CODE_NAMESPACE, - TMP_CODE_FILEPATH, - TMP_CODE_LINENO, - TMP_HTTP_METHOD, - TMP_HTTP_URL, - TMP_HTTP_TARGET, - TMP_HTTP_HOST, - TMP_HTTP_SCHEME, - TMP_HTTP_STATUS_CODE, - TMP_HTTP_FLAVOR, - TMP_HTTP_USER_AGENT, - TMP_HTTP_REQUEST_CONTENT_LENGTH, - TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_RESPONSE_CONTENT_LENGTH, - TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_SERVER_NAME, - TMP_HTTP_ROUTE, - TMP_HTTP_CLIENT_IP, - TMP_AWS_DYNAMODB_TABLE_NAMES, - TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, - TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, - TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, - TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, - TMP_AWS_DYNAMODB_CONSISTENT_READ, - TMP_AWS_DYNAMODB_PROJECTION, - TMP_AWS_DYNAMODB_LIMIT, - TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, - TMP_AWS_DYNAMODB_INDEX_NAME, - TMP_AWS_DYNAMODB_SELECT, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, - TMP_AWS_DYNAMODB_TABLE_COUNT, - TMP_AWS_DYNAMODB_SCAN_FORWARD, - TMP_AWS_DYNAMODB_SEGMENT, - TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, - TMP_AWS_DYNAMODB_COUNT, - TMP_AWS_DYNAMODB_SCANNED_COUNT, - TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, - TMP_MESSAGING_SYSTEM, - TMP_MESSAGING_DESTINATION, - TMP_MESSAGING_DESTINATION_KIND, - TMP_MESSAGING_TEMP_DESTINATION, - TMP_MESSAGING_PROTOCOL, - TMP_MESSAGING_PROTOCOL_VERSION, - TMP_MESSAGING_URL, - TMP_MESSAGING_MESSAGE_ID, - TMP_MESSAGING_CONVERSATION_ID, - TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, - TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, - TMP_MESSAGING_OPERATION, - TMP_MESSAGING_CONSUMER_ID, - TMP_MESSAGING_RABBITMQ_ROUTING_KEY, - TMP_MESSAGING_KAFKA_MESSAGE_KEY, - TMP_MESSAGING_KAFKA_CONSUMER_GROUP, - TMP_MESSAGING_KAFKA_CLIENT_ID, - TMP_MESSAGING_KAFKA_PARTITION, - TMP_MESSAGING_KAFKA_TOMBSTONE, - TMP_RPC_SYSTEM, - TMP_RPC_SERVICE, - TMP_RPC_METHOD, - TMP_RPC_GRPC_STATUS_CODE, - TMP_RPC_JSONRPC_VERSION, - TMP_RPC_JSONRPC_REQUEST_ID, - TMP_RPC_JSONRPC_ERROR_CODE, - TMP_RPC_JSONRPC_ERROR_MESSAGE, - TMP_MESSAGE_TYPE, - TMP_MESSAGE_ID, - TMP_MESSAGE_COMPRESSED_SIZE, - TMP_MESSAGE_UNCOMPRESSED_SIZE, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for DbSystemValues enum definition - * - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_DBSYSTEMVALUES_OTHER_SQL = 'other_sql'; - const TMP_DBSYSTEMVALUES_MSSQL = 'mssql'; - const TMP_DBSYSTEMVALUES_MYSQL = 'mysql'; - const TMP_DBSYSTEMVALUES_ORACLE = 'oracle'; - const TMP_DBSYSTEMVALUES_DB2 = 'db2'; - const TMP_DBSYSTEMVALUES_POSTGRESQL = 'postgresql'; - const TMP_DBSYSTEMVALUES_REDSHIFT = 'redshift'; - const TMP_DBSYSTEMVALUES_HIVE = 'hive'; - const TMP_DBSYSTEMVALUES_CLOUDSCAPE = 'cloudscape'; - const TMP_DBSYSTEMVALUES_HSQLDB = 'hsqldb'; - const TMP_DBSYSTEMVALUES_PROGRESS = 'progress'; - const TMP_DBSYSTEMVALUES_MAXDB = 'maxdb'; - const TMP_DBSYSTEMVALUES_HANADB = 'hanadb'; - const TMP_DBSYSTEMVALUES_INGRES = 'ingres'; - const TMP_DBSYSTEMVALUES_FIRSTSQL = 'firstsql'; - const TMP_DBSYSTEMVALUES_EDB = 'edb'; - const TMP_DBSYSTEMVALUES_CACHE = 'cache'; - const TMP_DBSYSTEMVALUES_ADABAS = 'adabas'; - const TMP_DBSYSTEMVALUES_FIREBIRD = 'firebird'; - const TMP_DBSYSTEMVALUES_DERBY = 'derby'; - const TMP_DBSYSTEMVALUES_FILEMAKER = 'filemaker'; - const TMP_DBSYSTEMVALUES_INFORMIX = 'informix'; - const TMP_DBSYSTEMVALUES_INSTANTDB = 'instantdb'; - const TMP_DBSYSTEMVALUES_INTERBASE = 'interbase'; - const TMP_DBSYSTEMVALUES_MARIADB = 'mariadb'; - const TMP_DBSYSTEMVALUES_NETEZZA = 'netezza'; - const TMP_DBSYSTEMVALUES_PERVASIVE = 'pervasive'; - const TMP_DBSYSTEMVALUES_POINTBASE = 'pointbase'; - const TMP_DBSYSTEMVALUES_SQLITE = 'sqlite'; - const TMP_DBSYSTEMVALUES_SYBASE = 'sybase'; - const TMP_DBSYSTEMVALUES_TERADATA = 'teradata'; - const TMP_DBSYSTEMVALUES_VERTICA = 'vertica'; - const TMP_DBSYSTEMVALUES_H2 = 'h2'; - const TMP_DBSYSTEMVALUES_COLDFUSION = 'coldfusion'; - const TMP_DBSYSTEMVALUES_CASSANDRA = 'cassandra'; - const TMP_DBSYSTEMVALUES_HBASE = 'hbase'; - const TMP_DBSYSTEMVALUES_MONGODB = 'mongodb'; - const TMP_DBSYSTEMVALUES_REDIS = 'redis'; - const TMP_DBSYSTEMVALUES_COUCHBASE = 'couchbase'; - const TMP_DBSYSTEMVALUES_COUCHDB = 'couchdb'; - const TMP_DBSYSTEMVALUES_COSMOSDB = 'cosmosdb'; - const TMP_DBSYSTEMVALUES_DYNAMODB = 'dynamodb'; - const TMP_DBSYSTEMVALUES_NEO4J = 'neo4j'; - const TMP_DBSYSTEMVALUES_GEODE = 'geode'; - const TMP_DBSYSTEMVALUES_ELASTICSEARCH = 'elasticsearch'; - const TMP_DBSYSTEMVALUES_MEMCACHED = 'memcached'; - const TMP_DBSYSTEMVALUES_COCKROACHDB = 'cockroachdb'; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL. - */ - SemanticAttributes.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MSSQL. - */ - SemanticAttributes.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MYSQL. - */ - SemanticAttributes.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ORACLE. - */ - SemanticAttributes.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DB2. - */ - SemanticAttributes.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL. - */ - SemanticAttributes.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT. - */ - SemanticAttributes.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HIVE. - */ - SemanticAttributes.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE. - */ - SemanticAttributes.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HSQLDB. - */ - SemanticAttributes.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PROGRESS. - */ - SemanticAttributes.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MAXDB. - */ - SemanticAttributes.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HANADB. - */ - SemanticAttributes.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INGRES. - */ - SemanticAttributes.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL. - */ - SemanticAttributes.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_EDB. - */ - SemanticAttributes.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CACHE. - */ - SemanticAttributes.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ADABAS. - */ - SemanticAttributes.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD. - */ - SemanticAttributes.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DERBY. - */ - SemanticAttributes.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER. - */ - SemanticAttributes.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INFORMIX. - */ - SemanticAttributes.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB. - */ - SemanticAttributes.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INTERBASE. - */ - SemanticAttributes.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MARIADB. - */ - SemanticAttributes.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NETEZZA. - */ - SemanticAttributes.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE. - */ - SemanticAttributes.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POINTBASE. - */ - SemanticAttributes.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SQLITE. - */ - SemanticAttributes.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SYBASE. - */ - SemanticAttributes.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_TERADATA. - */ - SemanticAttributes.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_VERTICA. - */ - SemanticAttributes.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_H2. - */ - SemanticAttributes.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION. - */ - SemanticAttributes.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA. - */ - SemanticAttributes.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HBASE. - */ - SemanticAttributes.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MONGODB. - */ - SemanticAttributes.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDIS. - */ - SemanticAttributes.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE. - */ - SemanticAttributes.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHDB. - */ - SemanticAttributes.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB. - */ - SemanticAttributes.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB. - */ - SemanticAttributes.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NEO4J. - */ - SemanticAttributes.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_GEODE. - */ - SemanticAttributes.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH. - */ - SemanticAttributes.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED. - */ - SemanticAttributes.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB. - */ - SemanticAttributes.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; - /** - * The constant map of values for DbSystemValues. - * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification. - */ - SemanticAttributes.DbSystemValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_DBSYSTEMVALUES_OTHER_SQL, - TMP_DBSYSTEMVALUES_MSSQL, - TMP_DBSYSTEMVALUES_MYSQL, - TMP_DBSYSTEMVALUES_ORACLE, - TMP_DBSYSTEMVALUES_DB2, - TMP_DBSYSTEMVALUES_POSTGRESQL, - TMP_DBSYSTEMVALUES_REDSHIFT, - TMP_DBSYSTEMVALUES_HIVE, - TMP_DBSYSTEMVALUES_CLOUDSCAPE, - TMP_DBSYSTEMVALUES_HSQLDB, - TMP_DBSYSTEMVALUES_PROGRESS, - TMP_DBSYSTEMVALUES_MAXDB, - TMP_DBSYSTEMVALUES_HANADB, - TMP_DBSYSTEMVALUES_INGRES, - TMP_DBSYSTEMVALUES_FIRSTSQL, - TMP_DBSYSTEMVALUES_EDB, - TMP_DBSYSTEMVALUES_CACHE, - TMP_DBSYSTEMVALUES_ADABAS, - TMP_DBSYSTEMVALUES_FIREBIRD, - TMP_DBSYSTEMVALUES_DERBY, - TMP_DBSYSTEMVALUES_FILEMAKER, - TMP_DBSYSTEMVALUES_INFORMIX, - TMP_DBSYSTEMVALUES_INSTANTDB, - TMP_DBSYSTEMVALUES_INTERBASE, - TMP_DBSYSTEMVALUES_MARIADB, - TMP_DBSYSTEMVALUES_NETEZZA, - TMP_DBSYSTEMVALUES_PERVASIVE, - TMP_DBSYSTEMVALUES_POINTBASE, - TMP_DBSYSTEMVALUES_SQLITE, - TMP_DBSYSTEMVALUES_SYBASE, - TMP_DBSYSTEMVALUES_TERADATA, - TMP_DBSYSTEMVALUES_VERTICA, - TMP_DBSYSTEMVALUES_H2, - TMP_DBSYSTEMVALUES_COLDFUSION, - TMP_DBSYSTEMVALUES_CASSANDRA, - TMP_DBSYSTEMVALUES_HBASE, - TMP_DBSYSTEMVALUES_MONGODB, - TMP_DBSYSTEMVALUES_REDIS, - TMP_DBSYSTEMVALUES_COUCHBASE, - TMP_DBSYSTEMVALUES_COUCHDB, - TMP_DBSYSTEMVALUES_COSMOSDB, - TMP_DBSYSTEMVALUES_DYNAMODB, - TMP_DBSYSTEMVALUES_NEO4J, - TMP_DBSYSTEMVALUES_GEODE, - TMP_DBSYSTEMVALUES_ELASTICSEARCH, - TMP_DBSYSTEMVALUES_MEMCACHED, - TMP_DBSYSTEMVALUES_COCKROACHDB, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for DbCassandraConsistencyLevelValues enum definition - * - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = 'all'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = 'each_quorum'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = 'quorum'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = 'local_quorum'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = 'one'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = 'two'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = 'three'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = 'local_one'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = 'any'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = 'serial'; - const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = 'local_serial'; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL. - */ - SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; - /** - * The constant map of values for DbCassandraConsistencyLevelValues. - * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification. - */ - SemanticAttributes.DbCassandraConsistencyLevelValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for FaasTriggerValues enum definition - * - * Type of the trigger on which the function is executed. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_FAASTRIGGERVALUES_DATASOURCE = 'datasource'; - const TMP_FAASTRIGGERVALUES_HTTP = 'http'; - const TMP_FAASTRIGGERVALUES_PUBSUB = 'pubsub'; - const TMP_FAASTRIGGERVALUES_TIMER = 'timer'; - const TMP_FAASTRIGGERVALUES_OTHER = 'other'; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE. - */ - SemanticAttributes.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_HTTP. - */ - SemanticAttributes.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB. - */ - SemanticAttributes.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_TIMER. - */ - SemanticAttributes.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_OTHER. - */ - SemanticAttributes.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; - /** - * The constant map of values for FaasTriggerValues. - * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification. - */ - SemanticAttributes.FaasTriggerValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_FAASTRIGGERVALUES_DATASOURCE, - TMP_FAASTRIGGERVALUES_HTTP, - TMP_FAASTRIGGERVALUES_PUBSUB, - TMP_FAASTRIGGERVALUES_TIMER, - TMP_FAASTRIGGERVALUES_OTHER, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for FaasDocumentOperationValues enum definition - * - * Describes the type of the operation that was performed on the data. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = 'insert'; - const TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = 'edit'; - const TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = 'delete'; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT. - */ - SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT. - */ - SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE. - */ - SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; - /** - * The constant map of values for FaasDocumentOperationValues. - * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification. - */ - SemanticAttributes.FaasDocumentOperationValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, - TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, - TMP_FAASDOCUMENTOPERATIONVALUES_DELETE, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for FaasInvokedProviderValues enum definition - * - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud'; - const TMP_FAASINVOKEDPROVIDERVALUES_AWS = 'aws'; - const TMP_FAASINVOKEDPROVIDERVALUES_AZURE = 'azure'; - const TMP_FAASINVOKEDPROVIDERVALUES_GCP = 'gcp'; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD. - */ - SemanticAttributes.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS. - */ - SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE. - */ - SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP. - */ - SemanticAttributes.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; - /** - * The constant map of values for FaasInvokedProviderValues. - * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification. - */ - SemanticAttributes.FaasInvokedProviderValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_FAASINVOKEDPROVIDERVALUES_AWS, - TMP_FAASINVOKEDPROVIDERVALUES_AZURE, - TMP_FAASINVOKEDPROVIDERVALUES_GCP, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for NetTransportValues enum definition - * - * Transport protocol used. See note below. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_NETTRANSPORTVALUES_IP_TCP = 'ip_tcp'; - const TMP_NETTRANSPORTVALUES_IP_UDP = 'ip_udp'; - const TMP_NETTRANSPORTVALUES_IP = 'ip'; - const TMP_NETTRANSPORTVALUES_UNIX = 'unix'; - const TMP_NETTRANSPORTVALUES_PIPE = 'pipe'; - const TMP_NETTRANSPORTVALUES_INPROC = 'inproc'; - const TMP_NETTRANSPORTVALUES_OTHER = 'other'; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP. - */ - SemanticAttributes.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP. - */ - SemanticAttributes.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP. - */ - SemanticAttributes.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_UNIX. - */ - SemanticAttributes.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_PIPE. - */ - SemanticAttributes.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_INPROC. - */ - SemanticAttributes.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_OTHER. - */ - SemanticAttributes.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; - /** - * The constant map of values for NetTransportValues. - * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification. - */ - SemanticAttributes.NetTransportValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_NETTRANSPORTVALUES_IP_TCP, - TMP_NETTRANSPORTVALUES_IP_UDP, - TMP_NETTRANSPORTVALUES_IP, - TMP_NETTRANSPORTVALUES_UNIX, - TMP_NETTRANSPORTVALUES_PIPE, - TMP_NETTRANSPORTVALUES_INPROC, - TMP_NETTRANSPORTVALUES_OTHER, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for NetHostConnectionTypeValues enum definition - * - * The internet connection type currently being used by the host. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = 'wifi'; - const TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = 'wired'; - const TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = 'cell'; - const TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = 'unavailable'; - const TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = 'unknown'; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NET_HOST_CONNECTION_TYPE_VALUE_WIFI. - */ - SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NET_HOST_CONNECTION_TYPE_VALUE_WIRED. - */ - SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NET_HOST_CONNECTION_TYPE_VALUE_CELL. - */ - SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NET_HOST_CONNECTION_TYPE_VALUE_UNAVAILABLE. - */ - SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NET_HOST_CONNECTION_TYPE_VALUE_UNKNOWN. - */ - SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; - /** - * The constant map of values for NetHostConnectionTypeValues. - * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification. - */ - SemanticAttributes.NetHostConnectionTypeValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, - TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, - TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for NetHostConnectionSubtypeValues enum definition - * - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = 'gprs'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = 'edge'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = 'umts'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = 'cdma'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = 'evdo_0'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = 'evdo_a'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = 'cdma2000_1xrtt'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = 'hsdpa'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = 'hsupa'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = 'hspa'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = 'iden'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = 'evdo_b'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = 'lte'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = 'ehrpd'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = 'hspap'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = 'gsm'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = 'td_scdma'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = 'iwlan'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = 'nr'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = 'nrnsa'; - const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = 'lte_ca'; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_GPRS. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_EDGE. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_UMTS. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_CDMA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_EVDO_0. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_EVDO_A. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_HSDPA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_HSUPA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_HSPA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_IDEN. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_EVDO_B. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_LTE. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_EHRPD. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_HSPAP. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_GSM. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_TD_SCDMA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_IWLAN. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_NR. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_NRNSA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NET_HOST_CONNECTION_SUBTYPE_VALUE_LTE_CA. - */ - SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; - /** - * The constant map of values for NetHostConnectionSubtypeValues. - * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification. - */ - SemanticAttributes.NetHostConnectionSubtypeValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for HttpFlavorValues enum definition - * - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_HTTPFLAVORVALUES_HTTP_1_0 = '1.0'; - const TMP_HTTPFLAVORVALUES_HTTP_1_1 = '1.1'; - const TMP_HTTPFLAVORVALUES_HTTP_2_0 = '2.0'; - const TMP_HTTPFLAVORVALUES_SPDY = 'SPDY'; - const TMP_HTTPFLAVORVALUES_QUIC = 'QUIC'; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0. - */ - SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1. - */ - SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0. - */ - SemanticAttributes.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_SPDY. - */ - SemanticAttributes.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_QUIC. - */ - SemanticAttributes.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; - /** - * The constant map of values for HttpFlavorValues. - * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification. - */ - SemanticAttributes.HttpFlavorValues = { - HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, - HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, - HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, - SPDY: TMP_HTTPFLAVORVALUES_SPDY, - QUIC: TMP_HTTPFLAVORVALUES_QUIC, - }; - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for MessagingDestinationKindValues enum definition - * - * The kind of message destination. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = 'queue'; - const TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = 'topic'; - /** - * The kind of message destination. - * - * @deprecated Use MESSAGING_DESTINATION_KIND_VALUE_QUEUE. - */ - SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; - /** - * The kind of message destination. - * - * @deprecated Use MESSAGING_DESTINATION_KIND_VALUE_TOPIC. - */ - SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; - /** - * The constant map of values for MessagingDestinationKindValues. - * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification. - */ - SemanticAttributes.MessagingDestinationKindValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, - TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for MessagingOperationValues enum definition - * - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_MESSAGINGOPERATIONVALUES_RECEIVE = 'receive'; - const TMP_MESSAGINGOPERATIONVALUES_PROCESS = 'process'; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_VALUE_RECEIVE. - */ - SemanticAttributes.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_VALUE_PROCESS. - */ - SemanticAttributes.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; - /** - * The constant map of values for MessagingOperationValues. - * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification. - */ - SemanticAttributes.MessagingOperationValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_MESSAGINGOPERATIONVALUES_RECEIVE, - TMP_MESSAGINGOPERATIONVALUES_PROCESS, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for RpcGrpcStatusCodeValues enum definition - * - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; - const TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; - const TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; - const TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; - const TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; - const TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; - const TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; - const TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; - const TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; - const TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; - const TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; - const TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; - const TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; - const TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; - const TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; - const TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; - const TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED. - */ - SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; - /** - * The constant map of values for RpcGrpcStatusCodeValues. - * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification. - */ - SemanticAttributes.RpcGrpcStatusCodeValues = { - OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, - CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, - UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, - INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, - DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, - NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, - ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, - PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, - RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, - FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, - ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, - OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, - UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, - INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, - UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, - DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, - UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, - }; - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for MessageTypeValues enum definition - * - * Whether this is a received or sent message. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_MESSAGETYPEVALUES_SENT = 'SENT'; - const TMP_MESSAGETYPEVALUES_RECEIVED = 'RECEIVED'; - /** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_SENT. - */ - SemanticAttributes.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; - /** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED. - */ - SemanticAttributes.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; - /** - * The constant map of values for MessageTypeValues. - * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification. - */ - SemanticAttributes.MessageTypeValues = - /*#__PURE__*/ (0, utils_1$1.createConstMap)([ - TMP_MESSAGETYPEVALUES_SENT, - TMP_MESSAGETYPEVALUES_RECEIVED, - ]); - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var __createBinding = (index.commonjsGlobal && index.commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = (index.commonjsGlobal && index.commonjsGlobal.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - /* eslint-disable no-restricted-syntax -- - * These re-exports are only of constants, only one-level deep at this point, - * and should not cause problems for tree-shakers. - */ - __exportStar(SemanticAttributes, exports); - - } (trace)); - - var resource = {}; - - var SemanticResourceAttributes = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(SemanticResourceAttributes, "__esModule", { value: true }); - SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_CONTAINER_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_POD_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_POD_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_NAMESPACE_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_CLUSTER_NAME = SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_VERSION = SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_ID = SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_NAME = SemanticResourceAttributes.SEMRESATTRS_HOST_ARCH = SemanticResourceAttributes.SEMRESATTRS_HOST_TYPE = SemanticResourceAttributes.SEMRESATTRS_HOST_NAME = SemanticResourceAttributes.SEMRESATTRS_HOST_ID = SemanticResourceAttributes.SEMRESATTRS_FAAS_MAX_MEMORY = SemanticResourceAttributes.SEMRESATTRS_FAAS_INSTANCE = SemanticResourceAttributes.SEMRESATTRS_FAAS_VERSION = SemanticResourceAttributes.SEMRESATTRS_FAAS_ID = SemanticResourceAttributes.SEMRESATTRS_FAAS_NAME = SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_NAME = SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = SemanticResourceAttributes.SEMRESATTRS_DEVICE_ID = SemanticResourceAttributes.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_TAG = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_NAME = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_RUNTIME = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_ID = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_NAME = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_ARNS = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_NAMES = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_ARNS = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_NAMES = SemanticResourceAttributes.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_REVISION = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_FAMILY = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_ARN = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = SemanticResourceAttributes.SEMRESATTRS_CLOUD_PLATFORM = SemanticResourceAttributes.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = SemanticResourceAttributes.SEMRESATTRS_CLOUD_REGION = SemanticResourceAttributes.SEMRESATTRS_CLOUD_ACCOUNT_ID = SemanticResourceAttributes.SEMRESATTRS_CLOUD_PROVIDER = void 0; - SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_AKS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_VM = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_LAMBDA = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EKS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ECS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EC2 = SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = SemanticResourceAttributes.CloudProviderValues = SemanticResourceAttributes.CLOUDPROVIDERVALUES_GCP = SemanticResourceAttributes.CLOUDPROVIDERVALUES_AZURE = SemanticResourceAttributes.CLOUDPROVIDERVALUES_AWS = SemanticResourceAttributes.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = SemanticResourceAttributes.SemanticResourceAttributes = SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_DESCRIPTION = SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_VERSION = SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_NAME = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_AUTO_VERSION = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_VERSION = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_NAME = SemanticResourceAttributes.SEMRESATTRS_SERVICE_VERSION = SemanticResourceAttributes.SEMRESATTRS_SERVICE_INSTANCE_ID = SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAMESPACE = SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAME = SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_VERSION = SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_NAME = SemanticResourceAttributes.SEMRESATTRS_PROCESS_OWNER = SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_ARGS = SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_LINE = SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND = SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = SemanticResourceAttributes.SEMRESATTRS_PROCESS_PID = SemanticResourceAttributes.SEMRESATTRS_OS_VERSION = SemanticResourceAttributes.SEMRESATTRS_OS_NAME = SemanticResourceAttributes.SEMRESATTRS_OS_DESCRIPTION = SemanticResourceAttributes.SEMRESATTRS_OS_TYPE = SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; - SemanticResourceAttributes.TelemetrySdkLanguageValues = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_WEBJS = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_RUBY = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PYTHON = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PHP = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_NODEJS = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_JAVA = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_GO = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_ERLANG = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_DOTNET = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_CPP = SemanticResourceAttributes.OsTypeValues = SemanticResourceAttributes.OSTYPEVALUES_Z_OS = SemanticResourceAttributes.OSTYPEVALUES_SOLARIS = SemanticResourceAttributes.OSTYPEVALUES_AIX = SemanticResourceAttributes.OSTYPEVALUES_HPUX = SemanticResourceAttributes.OSTYPEVALUES_DRAGONFLYBSD = SemanticResourceAttributes.OSTYPEVALUES_OPENBSD = SemanticResourceAttributes.OSTYPEVALUES_NETBSD = SemanticResourceAttributes.OSTYPEVALUES_FREEBSD = SemanticResourceAttributes.OSTYPEVALUES_DARWIN = SemanticResourceAttributes.OSTYPEVALUES_LINUX = SemanticResourceAttributes.OSTYPEVALUES_WINDOWS = SemanticResourceAttributes.HostArchValues = SemanticResourceAttributes.HOSTARCHVALUES_X86 = SemanticResourceAttributes.HOSTARCHVALUES_PPC64 = SemanticResourceAttributes.HOSTARCHVALUES_PPC32 = SemanticResourceAttributes.HOSTARCHVALUES_IA64 = SemanticResourceAttributes.HOSTARCHVALUES_ARM64 = SemanticResourceAttributes.HOSTARCHVALUES_ARM32 = SemanticResourceAttributes.HOSTARCHVALUES_AMD64 = SemanticResourceAttributes.AwsEcsLaunchtypeValues = SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_FARGATE = SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_EC2 = SemanticResourceAttributes.CloudPlatformValues = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; - const utils_1 = utils; - //---------------------------------------------------------------------------------------------------------- - // DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2 - //---------------------------------------------------------------------------------------------------------- - //---------------------------------------------------------------------------------------------------------- - // Constant values for SemanticResourceAttributes - //---------------------------------------------------------------------------------------------------------- - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_CLOUD_PROVIDER = 'cloud.provider'; - const TMP_CLOUD_ACCOUNT_ID = 'cloud.account.id'; - const TMP_CLOUD_REGION = 'cloud.region'; - const TMP_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone'; - const TMP_CLOUD_PLATFORM = 'cloud.platform'; - const TMP_AWS_ECS_CONTAINER_ARN = 'aws.ecs.container.arn'; - const TMP_AWS_ECS_CLUSTER_ARN = 'aws.ecs.cluster.arn'; - const TMP_AWS_ECS_LAUNCHTYPE = 'aws.ecs.launchtype'; - const TMP_AWS_ECS_TASK_ARN = 'aws.ecs.task.arn'; - const TMP_AWS_ECS_TASK_FAMILY = 'aws.ecs.task.family'; - const TMP_AWS_ECS_TASK_REVISION = 'aws.ecs.task.revision'; - const TMP_AWS_EKS_CLUSTER_ARN = 'aws.eks.cluster.arn'; - const TMP_AWS_LOG_GROUP_NAMES = 'aws.log.group.names'; - const TMP_AWS_LOG_GROUP_ARNS = 'aws.log.group.arns'; - const TMP_AWS_LOG_STREAM_NAMES = 'aws.log.stream.names'; - const TMP_AWS_LOG_STREAM_ARNS = 'aws.log.stream.arns'; - const TMP_CONTAINER_NAME = 'container.name'; - const TMP_CONTAINER_ID = 'container.id'; - const TMP_CONTAINER_RUNTIME = 'container.runtime'; - const TMP_CONTAINER_IMAGE_NAME = 'container.image.name'; - const TMP_CONTAINER_IMAGE_TAG = 'container.image.tag'; - const TMP_DEPLOYMENT_ENVIRONMENT = 'deployment.environment'; - const TMP_DEVICE_ID = 'device.id'; - const TMP_DEVICE_MODEL_IDENTIFIER = 'device.model.identifier'; - const TMP_DEVICE_MODEL_NAME = 'device.model.name'; - const TMP_FAAS_NAME = 'faas.name'; - const TMP_FAAS_ID = 'faas.id'; - const TMP_FAAS_VERSION = 'faas.version'; - const TMP_FAAS_INSTANCE = 'faas.instance'; - const TMP_FAAS_MAX_MEMORY = 'faas.max_memory'; - const TMP_HOST_ID = 'host.id'; - const TMP_HOST_NAME = 'host.name'; - const TMP_HOST_TYPE = 'host.type'; - const TMP_HOST_ARCH = 'host.arch'; - const TMP_HOST_IMAGE_NAME = 'host.image.name'; - const TMP_HOST_IMAGE_ID = 'host.image.id'; - const TMP_HOST_IMAGE_VERSION = 'host.image.version'; - const TMP_K8S_CLUSTER_NAME = 'k8s.cluster.name'; - const TMP_K8S_NODE_NAME = 'k8s.node.name'; - const TMP_K8S_NODE_UID = 'k8s.node.uid'; - const TMP_K8S_NAMESPACE_NAME = 'k8s.namespace.name'; - const TMP_K8S_POD_UID = 'k8s.pod.uid'; - const TMP_K8S_POD_NAME = 'k8s.pod.name'; - const TMP_K8S_CONTAINER_NAME = 'k8s.container.name'; - const TMP_K8S_REPLICASET_UID = 'k8s.replicaset.uid'; - const TMP_K8S_REPLICASET_NAME = 'k8s.replicaset.name'; - const TMP_K8S_DEPLOYMENT_UID = 'k8s.deployment.uid'; - const TMP_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name'; - const TMP_K8S_STATEFULSET_UID = 'k8s.statefulset.uid'; - const TMP_K8S_STATEFULSET_NAME = 'k8s.statefulset.name'; - const TMP_K8S_DAEMONSET_UID = 'k8s.daemonset.uid'; - const TMP_K8S_DAEMONSET_NAME = 'k8s.daemonset.name'; - const TMP_K8S_JOB_UID = 'k8s.job.uid'; - const TMP_K8S_JOB_NAME = 'k8s.job.name'; - const TMP_K8S_CRONJOB_UID = 'k8s.cronjob.uid'; - const TMP_K8S_CRONJOB_NAME = 'k8s.cronjob.name'; - const TMP_OS_TYPE = 'os.type'; - const TMP_OS_DESCRIPTION = 'os.description'; - const TMP_OS_NAME = 'os.name'; - const TMP_OS_VERSION = 'os.version'; - const TMP_PROCESS_PID = 'process.pid'; - const TMP_PROCESS_EXECUTABLE_NAME = 'process.executable.name'; - const TMP_PROCESS_EXECUTABLE_PATH = 'process.executable.path'; - const TMP_PROCESS_COMMAND = 'process.command'; - const TMP_PROCESS_COMMAND_LINE = 'process.command_line'; - const TMP_PROCESS_COMMAND_ARGS = 'process.command_args'; - const TMP_PROCESS_OWNER = 'process.owner'; - const TMP_PROCESS_RUNTIME_NAME = 'process.runtime.name'; - const TMP_PROCESS_RUNTIME_VERSION = 'process.runtime.version'; - const TMP_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description'; - const TMP_SERVICE_NAME = 'service.name'; - const TMP_SERVICE_NAMESPACE = 'service.namespace'; - const TMP_SERVICE_INSTANCE_ID = 'service.instance.id'; - const TMP_SERVICE_VERSION = 'service.version'; - const TMP_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; - const TMP_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; - const TMP_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; - const TMP_TELEMETRY_AUTO_VERSION = 'telemetry.auto.version'; - const TMP_WEBENGINE_NAME = 'webengine.name'; - const TMP_WEBENGINE_VERSION = 'webengine.version'; - const TMP_WEBENGINE_DESCRIPTION = 'webengine.description'; - /** - * Name of the cloud provider. - * - * @deprecated use ATTR_CLOUD_PROVIDER - */ - SemanticResourceAttributes.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; - /** - * The cloud account ID the resource is assigned to. - * - * @deprecated use ATTR_CLOUD_ACCOUNT_ID - */ - SemanticResourceAttributes.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; - /** - * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations). - * - * @deprecated use ATTR_CLOUD_REGION - */ - SemanticResourceAttributes.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; - /** - * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. - * - * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud. - * - * @deprecated use ATTR_CLOUD_AVAILABILITY_ZONE - */ - SemanticResourceAttributes.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated use ATTR_CLOUD_PLATFORM - */ - SemanticResourceAttributes.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; - /** - * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - * - * @deprecated use ATTR_AWS_ECS_CONTAINER_ARN - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; - /** - * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - * - * @deprecated use ATTR_AWS_ECS_CLUSTER_ARN - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated use ATTR_AWS_ECS_LAUNCHTYPE - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; - /** - * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - * - * @deprecated use ATTR_AWS_ECS_TASK_ARN - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; - /** - * The task definition family this task definition is a member of. - * - * @deprecated use ATTR_AWS_ECS_TASK_FAMILY - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; - /** - * The revision for this task definition. - * - * @deprecated use ATTR_AWS_ECS_TASK_REVISION - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; - /** - * The ARN of an EKS cluster. - * - * @deprecated use ATTR_AWS_EKS_CLUSTER_ARN - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; - /** - * The name(s) of the AWS log group(s) an application is writing to. - * - * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group. - * - * @deprecated use ATTR_AWS_LOG_GROUP_NAMES - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; - /** - * The Amazon Resource Name(s) (ARN) of the AWS log group(s). - * - * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - * - * @deprecated use ATTR_AWS_LOG_GROUP_ARNS - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; - /** - * The name(s) of the AWS log stream(s) an application is writing to. - * - * @deprecated use ATTR_AWS_LOG_STREAM_NAMES - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; - /** - * The ARN(s) of the AWS log stream(s). - * - * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream. - * - * @deprecated use ATTR_AWS_LOG_STREAM_ARNS - */ - SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; - /** - * Container name. - * - * @deprecated use ATTR_CONTAINER_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; - /** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated. - * - * @deprecated use ATTR_CONTAINER_ID - */ - SemanticResourceAttributes.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; - /** - * The container runtime managing this container. - * - * @deprecated use ATTR_CONTAINER_RUNTIME - */ - SemanticResourceAttributes.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; - /** - * Name of the image the container was built on. - * - * @deprecated use ATTR_CONTAINER_IMAGE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; - /** - * Container image tag. - * - * @deprecated use ATTR_CONTAINER_IMAGE_TAG - */ - SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; - /** - * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier). - * - * @deprecated use ATTR_DEPLOYMENT_ENVIRONMENT - */ - SemanticResourceAttributes.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; - /** - * A unique identifier representing the device. - * - * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence. - * - * @deprecated use ATTR_DEVICE_ID - */ - SemanticResourceAttributes.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; - /** - * The model identifier for the device. - * - * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device. - * - * @deprecated use ATTR_DEVICE_MODEL_IDENTIFIER - */ - SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; - /** - * The marketing name for the device model. - * - * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative. - * - * @deprecated use ATTR_DEVICE_MODEL_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; - /** - * The name of the single function that this runtime instance executes. - * - * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes). - * - * @deprecated use ATTR_FAAS_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; - /** - * The unique ID of the single function that this runtime instance executes. - * - * Note: Depending on the cloud provider, use: - - * **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - Take care not to use the "invoked ARN" directly but replace any - [alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple - different aliases. - * **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names) - * **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id). - - On some providers, it may not be possible to determine the full ID at startup, - which is why this field cannot be made required. For example, on AWS the account ID - part of the ARN is not available without calling another AWS API - which may be deemed too slow for a short-running lambda function. - As an alternative, consider setting `faas.id` as a span attribute instead. - * - * @deprecated use ATTR_FAAS_ID - */ - SemanticResourceAttributes.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; - /** - * The immutable version of the function being executed. - * - * Note: Depending on the cloud provider and platform, use: - - * **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - (an integer represented as a decimal string). - * **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions) - (i.e., the function name plus the revision suffix). - * **Google Cloud Functions:** The value of the - [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - * **Azure Functions:** Not applicable. Do not set this attribute. - * - * @deprecated use ATTR_FAAS_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; - /** - * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version. - * - * Note: * **AWS Lambda:** Use the (full) log stream name. - * - * @deprecated use ATTR_FAAS_INSTANCE - */ - SemanticResourceAttributes.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; - /** - * The amount of memory available to the serverless function in MiB. - * - * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. - * - * @deprecated use ATTR_FAAS_MAX_MEMORY - */ - SemanticResourceAttributes.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; - /** - * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. - * - * @deprecated use ATTR_HOST_ID - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_ID = TMP_HOST_ID; - /** - * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. - * - * @deprecated use ATTR_HOST_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; - /** - * Type of host. For Cloud, this must be the machine type. - * - * @deprecated use ATTR_HOST_TYPE - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; - /** - * The CPU architecture the host system is running on. - * - * @deprecated use ATTR_HOST_ARCH - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; - /** - * Name of the VM image or OS install the host was instantiated from. - * - * @deprecated use ATTR_HOST_IMAGE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; - /** - * VM image ID. For Cloud, this value is from the provider. - * - * @deprecated use ATTR_HOST_IMAGE_ID - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; - /** - * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes). - * - * @deprecated use ATTR_HOST_IMAGE_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; - /** - * The name of the cluster. - * - * @deprecated use ATTR_K8S_CLUSTER_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; - /** - * The name of the Node. - * - * @deprecated use ATTR_K8S_NODE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; - /** - * The UID of the Node. - * - * @deprecated use ATTR_K8S_NODE_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; - /** - * The name of the namespace that the pod is running in. - * - * @deprecated use ATTR_K8S_NAMESPACE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; - /** - * The UID of the Pod. - * - * @deprecated use ATTR_K8S_POD_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; - /** - * The name of the Pod. - * - * @deprecated use ATTR_K8S_POD_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; - /** - * The name of the Container in a Pod template. - * - * @deprecated use ATTR_K8S_CONTAINER_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; - /** - * The UID of the ReplicaSet. - * - * @deprecated use ATTR_K8S_REPLICASET_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; - /** - * The name of the ReplicaSet. - * - * @deprecated use ATTR_K8S_REPLICASET_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; - /** - * The UID of the Deployment. - * - * @deprecated use ATTR_K8S_DEPLOYMENT_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; - /** - * The name of the Deployment. - * - * @deprecated use ATTR_K8S_DEPLOYMENT_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; - /** - * The UID of the StatefulSet. - * - * @deprecated use ATTR_K8S_STATEFULSET_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; - /** - * The name of the StatefulSet. - * - * @deprecated use ATTR_K8S_STATEFULSET_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; - /** - * The UID of the DaemonSet. - * - * @deprecated use ATTR_K8S_DAEMONSET_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; - /** - * The name of the DaemonSet. - * - * @deprecated use ATTR_K8S_DAEMONSET_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; - /** - * The UID of the Job. - * - * @deprecated use ATTR_K8S_JOB_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; - /** - * The name of the Job. - * - * @deprecated use ATTR_K8S_JOB_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; - /** - * The UID of the CronJob. - * - * @deprecated use ATTR_K8S_CRONJOB_UID - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; - /** - * The name of the CronJob. - * - * @deprecated use ATTR_K8S_CRONJOB_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; - /** - * The operating system type. - * - * @deprecated use ATTR_OS_TYPE - */ - SemanticResourceAttributes.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; - /** - * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands. - * - * @deprecated use ATTR_OS_DESCRIPTION - */ - SemanticResourceAttributes.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; - /** - * Human readable operating system name. - * - * @deprecated use ATTR_OS_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_OS_NAME = TMP_OS_NAME; - /** - * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes). - * - * @deprecated use ATTR_OS_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; - /** - * Process identifier (PID). - * - * @deprecated use ATTR_PROCESS_PID - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; - /** - * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`. - * - * @deprecated use ATTR_PROCESS_EXECUTABLE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; - /** - * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. - * - * @deprecated use ATTR_PROCESS_EXECUTABLE_PATH - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; - /** - * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. - * - * @deprecated use ATTR_PROCESS_COMMAND - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; - /** - * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead. - * - * @deprecated use ATTR_PROCESS_COMMAND_LINE - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; - /** - * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. - * - * @deprecated use ATTR_PROCESS_COMMAND_ARGS - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; - /** - * The username of the user that owns the process. - * - * @deprecated use ATTR_PROCESS_OWNER - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; - /** - * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. - * - * @deprecated use ATTR_PROCESS_RUNTIME_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; - /** - * The version of the runtime of this process, as returned by the runtime without modification. - * - * @deprecated use ATTR_PROCESS_RUNTIME_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; - /** - * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. - * - * @deprecated use ATTR_PROCESS_RUNTIME_DESCRIPTION - */ - SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; - /** - * Logical name of the service. - * - * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. - * - * @deprecated use ATTR_SERVICE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; - /** - * A namespace for `service.name`. - * - * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - * - * @deprecated use ATTR_SERVICE_NAMESPACE - */ - SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; - /** - * The string ID of the service instance. - * - * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). - * - * @deprecated use ATTR_SERVICE_INSTANCE_ID - */ - SemanticResourceAttributes.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; - /** - * The version string of the service API or implementation. - * - * @deprecated use ATTR_SERVICE_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; - /** - * The name of the telemetry SDK as defined above. - * - * @deprecated use ATTR_TELEMETRY_SDK_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; - /** - * The language of the telemetry SDK. - * - * @deprecated use ATTR_TELEMETRY_SDK_LANGUAGE - */ - SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; - /** - * The version string of the telemetry SDK. - * - * @deprecated use ATTR_TELEMETRY_SDK_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; - /** - * The version string of the auto instrumentation agent, if used. - * - * @deprecated use ATTR_TELEMETRY_AUTO_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; - /** - * The name of the web engine. - * - * @deprecated use ATTR_WEBENGINE_NAME - */ - SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; - /** - * The version of the web engine. - * - * @deprecated use ATTR_WEBENGINE_VERSION - */ - SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; - /** - * Additional description of the web engine (e.g. detailed version and edition information). - * - * @deprecated use ATTR_WEBENGINE_DESCRIPTION - */ - SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; - /** - * Create exported Value Map for SemanticResourceAttributes values - * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification - */ - SemanticResourceAttributes.SemanticResourceAttributes = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUD_PROVIDER, - TMP_CLOUD_ACCOUNT_ID, - TMP_CLOUD_REGION, - TMP_CLOUD_AVAILABILITY_ZONE, - TMP_CLOUD_PLATFORM, - TMP_AWS_ECS_CONTAINER_ARN, - TMP_AWS_ECS_CLUSTER_ARN, - TMP_AWS_ECS_LAUNCHTYPE, - TMP_AWS_ECS_TASK_ARN, - TMP_AWS_ECS_TASK_FAMILY, - TMP_AWS_ECS_TASK_REVISION, - TMP_AWS_EKS_CLUSTER_ARN, - TMP_AWS_LOG_GROUP_NAMES, - TMP_AWS_LOG_GROUP_ARNS, - TMP_AWS_LOG_STREAM_NAMES, - TMP_AWS_LOG_STREAM_ARNS, - TMP_CONTAINER_NAME, - TMP_CONTAINER_ID, - TMP_CONTAINER_RUNTIME, - TMP_CONTAINER_IMAGE_NAME, - TMP_CONTAINER_IMAGE_TAG, - TMP_DEPLOYMENT_ENVIRONMENT, - TMP_DEVICE_ID, - TMP_DEVICE_MODEL_IDENTIFIER, - TMP_DEVICE_MODEL_NAME, - TMP_FAAS_NAME, - TMP_FAAS_ID, - TMP_FAAS_VERSION, - TMP_FAAS_INSTANCE, - TMP_FAAS_MAX_MEMORY, - TMP_HOST_ID, - TMP_HOST_NAME, - TMP_HOST_TYPE, - TMP_HOST_ARCH, - TMP_HOST_IMAGE_NAME, - TMP_HOST_IMAGE_ID, - TMP_HOST_IMAGE_VERSION, - TMP_K8S_CLUSTER_NAME, - TMP_K8S_NODE_NAME, - TMP_K8S_NODE_UID, - TMP_K8S_NAMESPACE_NAME, - TMP_K8S_POD_UID, - TMP_K8S_POD_NAME, - TMP_K8S_CONTAINER_NAME, - TMP_K8S_REPLICASET_UID, - TMP_K8S_REPLICASET_NAME, - TMP_K8S_DEPLOYMENT_UID, - TMP_K8S_DEPLOYMENT_NAME, - TMP_K8S_STATEFULSET_UID, - TMP_K8S_STATEFULSET_NAME, - TMP_K8S_DAEMONSET_UID, - TMP_K8S_DAEMONSET_NAME, - TMP_K8S_JOB_UID, - TMP_K8S_JOB_NAME, - TMP_K8S_CRONJOB_UID, - TMP_K8S_CRONJOB_NAME, - TMP_OS_TYPE, - TMP_OS_DESCRIPTION, - TMP_OS_NAME, - TMP_OS_VERSION, - TMP_PROCESS_PID, - TMP_PROCESS_EXECUTABLE_NAME, - TMP_PROCESS_EXECUTABLE_PATH, - TMP_PROCESS_COMMAND, - TMP_PROCESS_COMMAND_LINE, - TMP_PROCESS_COMMAND_ARGS, - TMP_PROCESS_OWNER, - TMP_PROCESS_RUNTIME_NAME, - TMP_PROCESS_RUNTIME_VERSION, - TMP_PROCESS_RUNTIME_DESCRIPTION, - TMP_SERVICE_NAME, - TMP_SERVICE_NAMESPACE, - TMP_SERVICE_INSTANCE_ID, - TMP_SERVICE_VERSION, - TMP_TELEMETRY_SDK_NAME, - TMP_TELEMETRY_SDK_LANGUAGE, - TMP_TELEMETRY_SDK_VERSION, - TMP_TELEMETRY_AUTO_VERSION, - TMP_WEBENGINE_NAME, - TMP_WEBENGINE_VERSION, - TMP_WEBENGINE_DESCRIPTION, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for CloudProviderValues enum definition - * - * Name of the cloud provider. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud'; - const TMP_CLOUDPROVIDERVALUES_AWS = 'aws'; - const TMP_CLOUDPROVIDERVALUES_AZURE = 'azure'; - const TMP_CLOUDPROVIDERVALUES_GCP = 'gcp'; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD. - */ - SemanticResourceAttributes.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AWS. - */ - SemanticResourceAttributes.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE. - */ - SemanticResourceAttributes.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_GCP. - */ - SemanticResourceAttributes.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; - /** - * The constant map of values for CloudProviderValues. - * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification. - */ - SemanticResourceAttributes.CloudProviderValues = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_CLOUDPROVIDERVALUES_AWS, - TMP_CLOUDPROVIDERVALUES_AZURE, - TMP_CLOUDPROVIDERVALUES_GCP, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for CloudPlatformValues enum definition - * - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = 'alibaba_cloud_ecs'; - const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = 'alibaba_cloud_fc'; - const TMP_CLOUDPLATFORMVALUES_AWS_EC2 = 'aws_ec2'; - const TMP_CLOUDPLATFORMVALUES_AWS_ECS = 'aws_ecs'; - const TMP_CLOUDPLATFORMVALUES_AWS_EKS = 'aws_eks'; - const TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = 'aws_lambda'; - const TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = 'aws_elastic_beanstalk'; - const TMP_CLOUDPLATFORMVALUES_AZURE_VM = 'azure_vm'; - const TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = 'azure_container_instances'; - const TMP_CLOUDPLATFORMVALUES_AZURE_AKS = 'azure_aks'; - const TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = 'azure_functions'; - const TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = 'azure_app_service'; - const TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = 'gcp_compute_engine'; - const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = 'gcp_cloud_run'; - const TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = 'gcp_kubernetes_engine'; - const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = 'gcp_cloud_functions'; - const TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = 'gcp_app_engine'; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE. - */ - SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; - /** - * The constant map of values for CloudPlatformValues. - * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification. - */ - SemanticResourceAttributes.CloudPlatformValues = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, - TMP_CLOUDPLATFORMVALUES_AWS_EC2, - TMP_CLOUDPLATFORMVALUES_AWS_ECS, - TMP_CLOUDPLATFORMVALUES_AWS_EKS, - TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, - TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, - TMP_CLOUDPLATFORMVALUES_AZURE_VM, - TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, - TMP_CLOUDPLATFORMVALUES_AZURE_AKS, - TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, - TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, - TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for AwsEcsLaunchtypeValues enum definition - * - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_AWSECSLAUNCHTYPEVALUES_EC2 = 'ec2'; - const TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = 'fargate'; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2. - */ - SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE. - */ - SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; - /** - * The constant map of values for AwsEcsLaunchtypeValues. - * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification. - */ - SemanticResourceAttributes.AwsEcsLaunchtypeValues = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_AWSECSLAUNCHTYPEVALUES_EC2, - TMP_AWSECSLAUNCHTYPEVALUES_FARGATE, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for HostArchValues enum definition - * - * The CPU architecture the host system is running on. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_HOSTARCHVALUES_AMD64 = 'amd64'; - const TMP_HOSTARCHVALUES_ARM32 = 'arm32'; - const TMP_HOSTARCHVALUES_ARM64 = 'arm64'; - const TMP_HOSTARCHVALUES_IA64 = 'ia64'; - const TMP_HOSTARCHVALUES_PPC32 = 'ppc32'; - const TMP_HOSTARCHVALUES_PPC64 = 'ppc64'; - const TMP_HOSTARCHVALUES_X86 = 'x86'; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_AMD64. - */ - SemanticResourceAttributes.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM32. - */ - SemanticResourceAttributes.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM64. - */ - SemanticResourceAttributes.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_IA64. - */ - SemanticResourceAttributes.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC32. - */ - SemanticResourceAttributes.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC64. - */ - SemanticResourceAttributes.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_X86. - */ - SemanticResourceAttributes.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; - /** - * The constant map of values for HostArchValues. - * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification. - */ - SemanticResourceAttributes.HostArchValues = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_HOSTARCHVALUES_AMD64, - TMP_HOSTARCHVALUES_ARM32, - TMP_HOSTARCHVALUES_ARM64, - TMP_HOSTARCHVALUES_IA64, - TMP_HOSTARCHVALUES_PPC32, - TMP_HOSTARCHVALUES_PPC64, - TMP_HOSTARCHVALUES_X86, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for OsTypeValues enum definition - * - * The operating system type. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_OSTYPEVALUES_WINDOWS = 'windows'; - const TMP_OSTYPEVALUES_LINUX = 'linux'; - const TMP_OSTYPEVALUES_DARWIN = 'darwin'; - const TMP_OSTYPEVALUES_FREEBSD = 'freebsd'; - const TMP_OSTYPEVALUES_NETBSD = 'netbsd'; - const TMP_OSTYPEVALUES_OPENBSD = 'openbsd'; - const TMP_OSTYPEVALUES_DRAGONFLYBSD = 'dragonflybsd'; - const TMP_OSTYPEVALUES_HPUX = 'hpux'; - const TMP_OSTYPEVALUES_AIX = 'aix'; - const TMP_OSTYPEVALUES_SOLARIS = 'solaris'; - const TMP_OSTYPEVALUES_Z_OS = 'z_os'; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_WINDOWS. - */ - SemanticResourceAttributes.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_LINUX. - */ - SemanticResourceAttributes.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DARWIN. - */ - SemanticResourceAttributes.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_FREEBSD. - */ - SemanticResourceAttributes.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_NETBSD. - */ - SemanticResourceAttributes.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_OPENBSD. - */ - SemanticResourceAttributes.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD. - */ - SemanticResourceAttributes.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_HPUX. - */ - SemanticResourceAttributes.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_AIX. - */ - SemanticResourceAttributes.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_SOLARIS. - */ - SemanticResourceAttributes.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_Z_OS. - */ - SemanticResourceAttributes.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; - /** - * The constant map of values for OsTypeValues. - * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification. - */ - SemanticResourceAttributes.OsTypeValues = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_OSTYPEVALUES_WINDOWS, - TMP_OSTYPEVALUES_LINUX, - TMP_OSTYPEVALUES_DARWIN, - TMP_OSTYPEVALUES_FREEBSD, - TMP_OSTYPEVALUES_NETBSD, - TMP_OSTYPEVALUES_OPENBSD, - TMP_OSTYPEVALUES_DRAGONFLYBSD, - TMP_OSTYPEVALUES_HPUX, - TMP_OSTYPEVALUES_AIX, - TMP_OSTYPEVALUES_SOLARIS, - TMP_OSTYPEVALUES_Z_OS, - ]); - /* ---------------------------------------------------------------------------------------------------------- - * Constant values for TelemetrySdkLanguageValues enum definition - * - * The language of the telemetry SDK. - * ---------------------------------------------------------------------------------------------------------- */ - // Temporary local constants to assign to the individual exports and the namespaced version - // Required to avoid the namespace exports using the unminifiable export names for some package types - const TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = 'cpp'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = 'dotnet'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = 'erlang'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_GO = 'go'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = 'java'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = 'nodejs'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = 'php'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = 'python'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = 'ruby'; - const TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = 'webjs'; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. - */ - SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; - /** - * The constant map of values for TelemetrySdkLanguageValues. - * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification. - */ - SemanticResourceAttributes.TelemetrySdkLanguageValues = - /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, - TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, - TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, - TMP_TELEMETRYSDKLANGUAGEVALUES_GO, - TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, - TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, - TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, - TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, - TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, - TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS, - ]); - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var __createBinding = (index.commonjsGlobal && index.commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = (index.commonjsGlobal && index.commonjsGlobal.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - /* eslint-disable no-restricted-syntax -- - * These re-exports are only of constants, only one-level deep at this point, - * and should not cause problems for tree-shakers. - */ - __exportStar(SemanticResourceAttributes, exports); - - } (resource)); - - var stable_attributes = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(stable_attributes, "__esModule", { value: true }); - stable_attributes.HTTP_REQUEST_METHOD_VALUE_POST = stable_attributes.HTTP_REQUEST_METHOD_VALUE_PATCH = stable_attributes.HTTP_REQUEST_METHOD_VALUE_OPTIONS = stable_attributes.HTTP_REQUEST_METHOD_VALUE_HEAD = stable_attributes.HTTP_REQUEST_METHOD_VALUE_GET = stable_attributes.HTTP_REQUEST_METHOD_VALUE_DELETE = stable_attributes.HTTP_REQUEST_METHOD_VALUE_CONNECT = stable_attributes.HTTP_REQUEST_METHOD_VALUE_OTHER = stable_attributes.ATTR_HTTP_REQUEST_METHOD = stable_attributes.ATTR_HTTP_REQUEST_HEADER = stable_attributes.ATTR_EXCEPTION_TYPE = stable_attributes.ATTR_EXCEPTION_STACKTRACE = stable_attributes.ATTR_EXCEPTION_MESSAGE = stable_attributes.ATTR_EXCEPTION_ESCAPED = stable_attributes.ERROR_TYPE_VALUE_OTHER = stable_attributes.ATTR_ERROR_TYPE = stable_attributes.ATTR_CLIENT_PORT = stable_attributes.ATTR_CLIENT_ADDRESS = stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = stable_attributes.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = stable_attributes.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = stable_attributes.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = stable_attributes.ATTR_TELEMETRY_SDK_VERSION = stable_attributes.ATTR_TELEMETRY_SDK_NAME = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_GO = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = stable_attributes.ATTR_TELEMETRY_SDK_LANGUAGE = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = void 0; - stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = stable_attributes.ATTR_SIGNALR_CONNECTION_STATUS = stable_attributes.ATTR_SERVICE_VERSION = stable_attributes.ATTR_SERVICE_NAME = stable_attributes.ATTR_SERVER_PORT = stable_attributes.ATTR_SERVER_ADDRESS = stable_attributes.ATTR_OTEL_STATUS_DESCRIPTION = stable_attributes.OTEL_STATUS_CODE_VALUE_OK = stable_attributes.OTEL_STATUS_CODE_VALUE_ERROR = stable_attributes.ATTR_OTEL_STATUS_CODE = stable_attributes.ATTR_OTEL_SCOPE_VERSION = stable_attributes.ATTR_OTEL_SCOPE_NAME = stable_attributes.NETWORK_TYPE_VALUE_IPV6 = stable_attributes.NETWORK_TYPE_VALUE_IPV4 = stable_attributes.ATTR_NETWORK_TYPE = stable_attributes.NETWORK_TRANSPORT_VALUE_UNIX = stable_attributes.NETWORK_TRANSPORT_VALUE_UDP = stable_attributes.NETWORK_TRANSPORT_VALUE_TCP = stable_attributes.NETWORK_TRANSPORT_VALUE_QUIC = stable_attributes.NETWORK_TRANSPORT_VALUE_PIPE = stable_attributes.ATTR_NETWORK_TRANSPORT = stable_attributes.ATTR_NETWORK_PROTOCOL_VERSION = stable_attributes.ATTR_NETWORK_PROTOCOL_NAME = stable_attributes.ATTR_NETWORK_PEER_PORT = stable_attributes.ATTR_NETWORK_PEER_ADDRESS = stable_attributes.ATTR_NETWORK_LOCAL_PORT = stable_attributes.ATTR_NETWORK_LOCAL_ADDRESS = stable_attributes.JVM_THREAD_STATE_VALUE_WAITING = stable_attributes.JVM_THREAD_STATE_VALUE_TIMED_WAITING = stable_attributes.JVM_THREAD_STATE_VALUE_TERMINATED = stable_attributes.JVM_THREAD_STATE_VALUE_RUNNABLE = stable_attributes.JVM_THREAD_STATE_VALUE_NEW = stable_attributes.JVM_THREAD_STATE_VALUE_BLOCKED = stable_attributes.ATTR_JVM_THREAD_STATE = stable_attributes.ATTR_JVM_THREAD_DAEMON = stable_attributes.JVM_MEMORY_TYPE_VALUE_NON_HEAP = stable_attributes.JVM_MEMORY_TYPE_VALUE_HEAP = stable_attributes.ATTR_JVM_MEMORY_TYPE = stable_attributes.ATTR_JVM_MEMORY_POOL_NAME = stable_attributes.ATTR_JVM_GC_NAME = stable_attributes.ATTR_JVM_GC_ACTION = stable_attributes.ATTR_HTTP_ROUTE = stable_attributes.ATTR_HTTP_RESPONSE_STATUS_CODE = stable_attributes.ATTR_HTTP_RESPONSE_HEADER = stable_attributes.ATTR_HTTP_REQUEST_RESEND_COUNT = stable_attributes.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = stable_attributes.HTTP_REQUEST_METHOD_VALUE_TRACE = stable_attributes.HTTP_REQUEST_METHOD_VALUE_PUT = void 0; - stable_attributes.ATTR_USER_AGENT_ORIGINAL = stable_attributes.ATTR_URL_SCHEME = stable_attributes.ATTR_URL_QUERY = stable_attributes.ATTR_URL_PATH = stable_attributes.ATTR_URL_FULL = stable_attributes.ATTR_URL_FRAGMENT = stable_attributes.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = stable_attributes.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = stable_attributes.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = stable_attributes.ATTR_SIGNALR_TRANSPORT = void 0; - //---------------------------------------------------------------------------------------------------------- - // DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2 - //---------------------------------------------------------------------------------------------------------- - /** - * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason - * - * @example acquired - * - * @example request_canceled - */ - stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result'; - /** - * Enum value "acquired" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - */ - stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; - /** - * Enum value "endpoint_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - */ - stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; - /** - * Enum value "global_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - */ - stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; - /** - * Enum value "request_canceled" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - */ - stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; - /** - * The language of the telemetry SDK. - */ - stable_attributes.ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; - /** - * Enum value "cpp" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; - /** - * Enum value "dotnet" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; - /** - * Enum value "erlang" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; - /** - * Enum value "go" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; - /** - * Enum value "java" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; - /** - * Enum value "nodejs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; - /** - * Enum value "php" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; - /** - * Enum value "python" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; - /** - * Enum value "ruby" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; - /** - * Enum value "rust" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; - /** - * Enum value "swift" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; - /** - * Enum value "webjs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; - /** - * The name of the telemetry SDK as defined above. - * - * @example opentelemetry - * - * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`. - * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the - * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point - * or another suitable identifier depending on the language. - * The identifier `opentelemetry` is reserved and **MUST** **NOT** be used in this case. - * All custom identifiers **SHOULD** be stable across different versions of an implementation. - */ - stable_attributes.ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; - /** - * The version string of the telemetry SDK. - * - * @example 1.2.3 - */ - stable_attributes.ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; - /** - * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception. - * - * @example Contoso.MyHandler - */ - stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type'; - /** - * ASP.NET Core exception middleware handling result - * - * @example handled - * - * @example unhandled - */ - stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result'; - /** - * Enum value "aborted" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - */ - stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; - /** - * Enum value "handled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - */ - stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; - /** - * Enum value "skipped" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - */ - stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; - /** - * Enum value "unhandled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - */ - stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; - /** - * Rate limiting policy name. - * - * @example fixed - * - * @example sliding - * - * @example token - */ - stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy'; - /** - * Flag indicating if request was handled by the application pipeline. - * - * @example true - */ - stable_attributes.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled'; - /** - * A value that indicates whether the matched route is a fallback route. - * - * @example true - */ - stable_attributes.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback'; - /** - * Match result - success or failure - * - * @example success - * - * @example failure - */ - stable_attributes.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status'; - /** - * Enum value "failure" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - */ - stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; - /** - * Enum value "success" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - */ - stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; - /** - * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example client.example.com - * - * @example 10.1.2.80 - * - * @example /tmp/my.sock - * - * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available. - */ - stable_attributes.ATTR_CLIENT_ADDRESS = 'client.address'; - /** - * Client port number. - * - * @example 65123 - * - * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available. - */ - stable_attributes.ATTR_CLIENT_PORT = 'client.port'; - /** - * Describes a class of error the operation ended with. - * - * @example timeout - * - * @example java.net.UnknownHostException - * - * @example server_certificate_invalid - * - * @example 500 - * - * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. - * - * When `error.type` is set to a type (e.g., an exception type), its - * canonical class name identifying the type within the artifact **SHOULD** be used. - * - * Instrumentations **SHOULD** document the list of errors they report. - * - * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. - * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications - * should be prepared for `error.type` to have high cardinality at query time when no - * additional filters are applied. - * - * If the operation has completed successfully, instrumentations **SHOULD** **NOT** set `error.type`. - * - * If a specific domain defines its own set of error identifiers (such as HTTP or gRPC status codes), - * it's RECOMMENDED to: - * - * * Use a domain-specific attribute - * * Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. - */ - stable_attributes.ATTR_ERROR_TYPE = 'error.type'; - /** - * Enum value "_OTHER" for attribute {@link ATTR_ERROR_TYPE}. - */ - stable_attributes.ERROR_TYPE_VALUE_OTHER = "_OTHER"; - /** - * **SHOULD** be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. - * - * @note An exception is considered to have escaped (or left) the scope of a span, - * if that span is ended while the exception is still logically "in flight". - * This may be actually "in flight" in some languages (e.g. if the exception - * is passed to a Context manager's `__exit__` method in Python) but will - * usually be caught at the point of recording the exception in most languages. - * - * It is usually not possible to determine at the point where an exception is thrown - * whether it will escape the scope of a span. - * However, it is trivial to know that an exception - * will escape, if one checks for an active exception just before ending the span, - * as done in the [example for recording span exceptions](https://opentelemetry.io/docs/specs/semconv/exceptions/exceptions-spans/#recording-an-exception). - * - * It follows that an exception may still escape the scope of the span - * even if the `exception.escaped` attribute was not set or set to false, - * since the event might have been recorded at a time where it was not - * clear whether the exception will escape. - */ - stable_attributes.ATTR_EXCEPTION_ESCAPED = 'exception.escaped'; - /** - * The exception message. - * - * @example Division by zero - * - * @example Can't convert 'int' object to str implicitly - */ - stable_attributes.ATTR_EXCEPTION_MESSAGE = 'exception.message'; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @example "Exception in thread \"main\" java.lang.RuntimeException: Test exception\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)" - */ - stable_attributes.ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace'; - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @example java.net.ConnectException - * - * @example OSError - */ - stable_attributes.ATTR_EXCEPTION_TYPE = 'exception.type'; - /** - * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example http.request.header.content-type=["application/json"] - * - * @example http.request.header.x-forwarded-for=["1.2.3.4", "1.2.3.5"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * The `User-Agent` header is already captured in the `user_agent.original` attribute. Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * The attribute value **MUST** consist of either multiple header values as an array of strings or a single-item array containing a possibly comma-concatenated string, depending on the way the HTTP library provides access to headers. - */ - const ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; - stable_attributes.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; - /** - * HTTP request method. - * - * @example GET - * - * @example POST - * - * @example HEAD - * - * @note HTTP request method value **SHOULD** be "known" to the instrumentation. - * By default, this convention defines "known" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods) - * and the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html). - * - * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`. - * - * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override - * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named - * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods - * (this list **MUST** be a full override of the default known method, it is not a list of known methods in addition to the defaults). - * - * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly. - * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent. - * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value. - */ - stable_attributes.ATTR_HTTP_REQUEST_METHOD = 'http.request.method'; - /** - * Enum value "_OTHER" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; - /** - * Enum value "CONNECT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; - /** - * Enum value "DELETE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; - /** - * Enum value "GET" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; - /** - * Enum value "HEAD" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; - /** - * Enum value "OPTIONS" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; - /** - * Enum value "PATCH" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; - /** - * Enum value "POST" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; - /** - * Enum value "PUT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; - /** - * Enum value "TRACE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - */ - stable_attributes.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; - /** - * Original HTTP method sent by the client in the request line. - * - * @example GeT - * - * @example ACL - * - * @example foo - */ - stable_attributes.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original'; - /** - * The ordinal number of request resending attempt (for any reason, including redirects). - * - * @example 3 - * - * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other). - */ - stable_attributes.ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count'; - /** - * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example http.response.header.content-type=["application/json"] - * - * @example http.response.header.my-custom-header=["abc", "def"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * The attribute value **MUST** consist of either multiple header values as an array of strings or a single-item array containing a possibly comma-concatenated string, depending on the way the HTTP library provides access to headers. - */ - const ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; - stable_attributes.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; - /** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @example 200 - */ - stable_attributes.ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code'; - /** - * The matched route, that is, the path template in the format used by the respective server framework. - * - * @example /users/:userID? - * - * @example {controller}/{action}/{id?} - * - * @note MUST **NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can **NOT** substitute it. - * SHOULD include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one. - */ - stable_attributes.ATTR_HTTP_ROUTE = 'http.route'; - /** - * Name of the garbage collector action. - * - * @example end of minor GC - * - * @example end of major GC - * - * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). - */ - stable_attributes.ATTR_JVM_GC_ACTION = 'jvm.gc.action'; - /** - * Name of the garbage collector. - * - * @example G1 Young Generation - * - * @example G1 Old Generation - * - * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). - */ - stable_attributes.ATTR_JVM_GC_NAME = 'jvm.gc.name'; - /** - * Name of the memory pool. - * - * @example G1 Old Gen - * - * @example G1 Eden space - * - * @example G1 Survivor Space - * - * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). - */ - stable_attributes.ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name'; - /** - * The type of memory. - * - * @example heap - * - * @example non_heap - */ - stable_attributes.ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type'; - /** - * Enum value "heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - */ - stable_attributes.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; - /** - * Enum value "non_heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - */ - stable_attributes.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; - /** - * Whether the thread is daemon or not. - */ - stable_attributes.ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon'; - /** - * State of the thread. - * - * @example runnable - * - * @example blocked - */ - stable_attributes.ATTR_JVM_THREAD_STATE = 'jvm.thread.state'; - /** - * Enum value "blocked" for attribute {@link ATTR_JVM_THREAD_STATE}. - */ - stable_attributes.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; - /** - * Enum value "new" for attribute {@link ATTR_JVM_THREAD_STATE}. - */ - stable_attributes.JVM_THREAD_STATE_VALUE_NEW = "new"; - /** - * Enum value "runnable" for attribute {@link ATTR_JVM_THREAD_STATE}. - */ - stable_attributes.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; - /** - * Enum value "terminated" for attribute {@link ATTR_JVM_THREAD_STATE}. - */ - stable_attributes.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; - /** - * Enum value "timed_waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - */ - stable_attributes.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; - /** - * Enum value "waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - */ - stable_attributes.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; - /** - * Local address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * - * @example /tmp/my.sock - */ - stable_attributes.ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address'; - /** - * Local port number of the network connection. - * - * @example 65123 - */ - stable_attributes.ATTR_NETWORK_LOCAL_PORT = 'network.local.port'; - /** - * Peer address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * - * @example /tmp/my.sock - */ - stable_attributes.ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address'; - /** - * Peer port number of the network connection. - * - * @example 65123 - */ - stable_attributes.ATTR_NETWORK_PEER_PORT = 'network.peer.port'; - /** - * [OSI application layer](https://osi-model.com/application-layer/) or non-OSI equivalent. - * - * @example amqp - * - * @example http - * - * @example mqtt - * - * @note The value **SHOULD** be normalized to lowercase. - */ - stable_attributes.ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name'; - /** - * The actual version of the protocol used for network communication. - * - * @example 1.1 - * - * @example 2 - * - * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD** **NOT** be set. - */ - stable_attributes.ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version'; - /** - * [OSI transport layer](https://osi-model.com/transport-layer/) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication). - * - * @example tcp - * - * @example udp - * - * @note The value **SHOULD** be normalized to lowercase. - * - * Consider always setting the transport when setting a port number, since - * a port number is ambiguous without knowing the transport. For example - * different processes could be listening on TCP port 12345 and UDP port 12345. - */ - stable_attributes.ATTR_NETWORK_TRANSPORT = 'network.transport'; - /** - * Enum value "pipe" for attribute {@link ATTR_NETWORK_TRANSPORT}. - */ - stable_attributes.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; - /** - * Enum value "quic" for attribute {@link ATTR_NETWORK_TRANSPORT}. - */ - stable_attributes.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; - /** - * Enum value "tcp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - */ - stable_attributes.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; - /** - * Enum value "udp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - */ - stable_attributes.NETWORK_TRANSPORT_VALUE_UDP = "udp"; - /** - * Enum value "unix" for attribute {@link ATTR_NETWORK_TRANSPORT}. - */ - stable_attributes.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; - /** - * [OSI network layer](https://osi-model.com/network-layer/) or non-OSI equivalent. - * - * @example ipv4 - * - * @example ipv6 - * - * @note The value **SHOULD** be normalized to lowercase. - */ - stable_attributes.ATTR_NETWORK_TYPE = 'network.type'; - /** - * Enum value "ipv4" for attribute {@link ATTR_NETWORK_TYPE}. - */ - stable_attributes.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; - /** - * Enum value "ipv6" for attribute {@link ATTR_NETWORK_TYPE}. - */ - stable_attributes.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; - /** - * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP). - * - * @example io.opentelemetry.contrib.mongodb - */ - stable_attributes.ATTR_OTEL_SCOPE_NAME = 'otel.scope.name'; - /** - * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - * - * @example 1.0.0 - */ - stable_attributes.ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version'; - /** - * Name of the code, either "OK" or "ERROR". **MUST** **NOT** be set if the status code is UNSET. - */ - stable_attributes.ATTR_OTEL_STATUS_CODE = 'otel.status_code'; - /** - * Enum value "ERROR" for attribute {@link ATTR_OTEL_STATUS_CODE}. - */ - stable_attributes.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; - /** - * Enum value "OK" for attribute {@link ATTR_OTEL_STATUS_CODE}. - */ - stable_attributes.OTEL_STATUS_CODE_VALUE_OK = "OK"; - /** - * Description of the Status if it has a value, otherwise not set. - * - * @example resource not found - */ - stable_attributes.ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description'; - /** - * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example example.com - * - * @example 10.1.2.80 - * - * @example /tmp/my.sock - * - * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available. - */ - stable_attributes.ATTR_SERVER_ADDRESS = 'server.address'; - /** - * Server port number. - * - * @example 80 - * - * @example 8080 - * - * @example 443 - * - * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available. - */ - stable_attributes.ATTR_SERVER_PORT = 'server.port'; - /** - * Logical name of the service. - * - * @example shoppingcart - * - * @note MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`. - */ - stable_attributes.ATTR_SERVICE_NAME = 'service.name'; - /** - * The version string of the service API or implementation. The format is not defined by these conventions. - * - * @example 2.0.0 - * - * @example a01dbef8a - */ - stable_attributes.ATTR_SERVICE_VERSION = 'service.version'; - /** - * SignalR HTTP connection closure status. - * - * @example app_shutdown - * - * @example timeout - */ - stable_attributes.ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status'; - /** - * Enum value "app_shutdown" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - */ - stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; - /** - * Enum value "normal_closure" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - */ - stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; - /** - * Enum value "timeout" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - */ - stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; - /** - * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) - * - * @example web_sockets - * - * @example long_polling - */ - stable_attributes.ATTR_SIGNALR_TRANSPORT = 'signalr.transport'; - /** - * Enum value "long_polling" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - */ - stable_attributes.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; - /** - * Enum value "server_sent_events" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - */ - stable_attributes.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; - /** - * Enum value "web_sockets" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - */ - stable_attributes.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; - /** - * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component - * - * @example SemConv - */ - stable_attributes.ATTR_URL_FRAGMENT = 'url.fragment'; - /** - * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) - * - * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv - * - * @example //localhost - * - * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless. - * `url.full` **MUST** **NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`. - * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed). Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it. - */ - stable_attributes.ATTR_URL_FULL = 'url.full'; - /** - * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component - * - * @example /search - * - * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it. - */ - stable_attributes.ATTR_URL_PATH = 'url.path'; - /** - * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component - * - * @example q=OpenTelemetry - * - * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it. - */ - stable_attributes.ATTR_URL_QUERY = 'url.query'; - /** - * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol. - * - * @example https - * - * @example ftp - * - * @example telnet - */ - stable_attributes.ATTR_URL_SCHEME = 'url.scheme'; - /** - * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client. - * - * @example CERN-LineMode/2.15 libwww/2.17b3 - * - * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1 - * - * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2 - */ - stable_attributes.ATTR_USER_AGENT_ORIGINAL = 'user_agent.original'; - - var stable_metrics = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(stable_metrics, "__esModule", { value: true }); - stable_metrics.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = stable_metrics.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = stable_metrics.METRIC_KESTREL_UPGRADED_CONNECTIONS = stable_metrics.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = stable_metrics.METRIC_KESTREL_REJECTED_CONNECTIONS = stable_metrics.METRIC_KESTREL_QUEUED_REQUESTS = stable_metrics.METRIC_KESTREL_QUEUED_CONNECTIONS = stable_metrics.METRIC_KESTREL_CONNECTION_DURATION = stable_metrics.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = stable_metrics.METRIC_KESTREL_ACTIVE_CONNECTIONS = stable_metrics.METRIC_JVM_THREAD_COUNT = stable_metrics.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = stable_metrics.METRIC_JVM_MEMORY_USED = stable_metrics.METRIC_JVM_MEMORY_LIMIT = stable_metrics.METRIC_JVM_MEMORY_COMMITTED = stable_metrics.METRIC_JVM_GC_DURATION = stable_metrics.METRIC_JVM_CPU_TIME = stable_metrics.METRIC_JVM_CPU_RECENT_UTILIZATION = stable_metrics.METRIC_JVM_CPU_COUNT = stable_metrics.METRIC_JVM_CLASS_UNLOADED = stable_metrics.METRIC_JVM_CLASS_LOADED = stable_metrics.METRIC_JVM_CLASS_COUNT = stable_metrics.METRIC_HTTP_SERVER_REQUEST_DURATION = stable_metrics.METRIC_HTTP_CLIENT_REQUEST_DURATION = stable_metrics.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = stable_metrics.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; - //---------------------------------------------------------------------------------------------------------- - // DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/register/stable/metrics.ts.j2 - //---------------------------------------------------------------------------------------------------------- - /** - * Number of exceptions caught by exception handling middleware. - * - * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = 'aspnetcore.diagnostics.exceptions'; - /** - * Number of requests that are currently active on the server that hold a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = 'aspnetcore.rate_limiting.active_request_leases'; - /** - * Number of requests that are currently queued, waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = 'aspnetcore.rate_limiting.queued_requests'; - /** - * The time the request spent in a queue waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = 'aspnetcore.rate_limiting.request.time_in_queue'; - /** - * The duration of rate limiting lease held by requests on the server. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = 'aspnetcore.rate_limiting.request_lease.duration'; - /** - * Number of requests that tried to acquire a rate limiting lease. - * - * @note Requests could be: - * - * * Rejected by global or endpoint rate limiting policies - * * Canceled while waiting for the lease. - * - * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = 'aspnetcore.rate_limiting.requests'; - /** - * Number of requests that were attempted to be matched to an endpoint. - * - * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = 'aspnetcore.routing.match_attempts'; - /** - * Duration of HTTP client requests. - */ - stable_metrics.METRIC_HTTP_CLIENT_REQUEST_DURATION = 'http.client.request.duration'; - /** - * Duration of HTTP server requests. - */ - stable_metrics.METRIC_HTTP_SERVER_REQUEST_DURATION = 'http.server.request.duration'; - /** - * Number of classes currently loaded. - */ - stable_metrics.METRIC_JVM_CLASS_COUNT = 'jvm.class.count'; - /** - * Number of classes loaded since JVM start. - */ - stable_metrics.METRIC_JVM_CLASS_LOADED = 'jvm.class.loaded'; - /** - * Number of classes unloaded since JVM start. - */ - stable_metrics.METRIC_JVM_CLASS_UNLOADED = 'jvm.class.unloaded'; - /** - * Number of processors available to the Java virtual machine. - */ - stable_metrics.METRIC_JVM_CPU_COUNT = 'jvm.cpu.count'; - /** - * Recent CPU utilization for the process as reported by the JVM. - * - * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()). - */ - stable_metrics.METRIC_JVM_CPU_RECENT_UTILIZATION = 'jvm.cpu.recent_utilization'; - /** - * CPU time used by the process as reported by the JVM. - */ - stable_metrics.METRIC_JVM_CPU_TIME = 'jvm.cpu.time'; - /** - * Duration of JVM garbage collection actions. - */ - stable_metrics.METRIC_JVM_GC_DURATION = 'jvm.gc.duration'; - /** - * Measure of memory committed. - */ - stable_metrics.METRIC_JVM_MEMORY_COMMITTED = 'jvm.memory.committed'; - /** - * Measure of max obtainable memory. - */ - stable_metrics.METRIC_JVM_MEMORY_LIMIT = 'jvm.memory.limit'; - /** - * Measure of memory used. - */ - stable_metrics.METRIC_JVM_MEMORY_USED = 'jvm.memory.used'; - /** - * Measure of memory used, as measured after the most recent garbage collection event on this pool. - */ - stable_metrics.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = 'jvm.memory.used_after_last_gc'; - /** - * Number of executing platform threads. - */ - stable_metrics.METRIC_JVM_THREAD_COUNT = 'jvm.thread.count'; - /** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_ACTIVE_CONNECTIONS = 'kestrel.active_connections'; - /** - * Number of TLS handshakes that are currently in progress on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = 'kestrel.active_tls_handshakes'; - /** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_CONNECTION_DURATION = 'kestrel.connection.duration'; - /** - * Number of connections that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_QUEUED_CONNECTIONS = 'kestrel.queued_connections'; - /** - * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_QUEUED_REQUESTS = 'kestrel.queued_requests'; - /** - * Number of connections rejected by the server. - * - * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`. - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_REJECTED_CONNECTIONS = 'kestrel.rejected_connections'; - /** - * The duration of TLS handshakes on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = 'kestrel.tls_handshake.duration'; - /** - * Number of connections that are currently upgraded (WebSockets). . - * - * @note The counter only tracks HTTP/1.1 connections. - * - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_KESTREL_UPGRADED_CONNECTIONS = 'kestrel.upgraded_connections'; - /** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = 'signalr.server.active_connections'; - /** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ - stable_metrics.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = 'signalr.server.connection.duration'; - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var __createBinding = (index.commonjsGlobal && index.commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = (index.commonjsGlobal && index.commonjsGlobal.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - /* eslint-disable no-restricted-syntax -- - * These re-exports are only of constants, only two-levels deep, and - * should not cause problems for tree-shakers. - */ - // Deprecated. These are kept around for compatibility purposes - __exportStar(trace, exports); - __exportStar(resource, exports); - // Use these instead - __exportStar(stable_attributes, exports); - __exportStar(stable_metrics, exports); - - } (src)); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var _a; - /** Constants describing the SDK in use */ - var SDK_INFO = (_a = {}, - _a[src.SEMRESATTRS_TELEMETRY_SDK_NAME] = 'opentelemetry', - _a[src.SEMRESATTRS_PROCESS_RUNTIME_NAME] = 'browser', - _a[src.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE] = src.TELEMETRYSDKLANGUAGEVALUES_WEBJS, - _a[src.SEMRESATTRS_TELEMETRY_SDK_VERSION] = VERSION$1, - _a); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - function unrefTimer(_timer) { } - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var NANOSECOND_DIGITS = 9; - var NANOSECOND_DIGITS_IN_MILLIS = 6; - var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS); - var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); - /** - * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]). - * @param epochMillis - */ - function millisToHrTime(epochMillis) { - var epochSeconds = epochMillis / 1000; - // Decimals only. - var seconds = Math.trunc(epochSeconds); - // Round sub-nanosecond accuracy to nanosecond. - var nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS); - return [seconds, nanos]; - } - function getTimeOrigin() { - var timeOrigin = otperformance.timeOrigin; - if (typeof timeOrigin !== 'number') { - var perf = otperformance; - timeOrigin = perf.timing && perf.timing.fetchStart; - } - return timeOrigin; - } - /** - * Returns an hrtime calculated via performance component. - * @param performanceNow - */ - function hrTime(performanceNow) { - var timeOrigin = millisToHrTime(getTimeOrigin()); - var now = millisToHrTime(typeof performanceNow === 'number' ? performanceNow : otperformance.now()); - return addHrTimes(timeOrigin, now); - } - /** - * - * Converts a TimeInput to an HrTime, defaults to _hrtime(). - * @param time + * Converts a TimeInput to an HrTime, defaults to _hrtime(). + * @param time */ function timeInputToHrTime(time) { // process.hrtime @@ -5615,8 +859,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param endTime */ function hrTimeDuration(startTime, endTime) { - var seconds = endTime[0] - startTime[0]; - var nanos = endTime[1] - startTime[1]; + let seconds = endTime[0] - startTime[0]; + let nanos = endTime[1] - startTime[1]; // overflow if (nanos < 0) { seconds -= 1; @@ -5662,7 +906,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Given 2 HrTime formatted times, return their sum as an HrTime. */ function addHrTimes(time1, time2) { - var out = [time1[0] + time2[0], time1[1] + time2[1]]; + const out = [time1[0] + time2[0], time1[1] + time2[1]]; // Nanoseconds if (out[1] >= SECOND_TO_NANOSECONDS) { out[1] -= SECOND_TO_NANOSECONDS; @@ -5706,33 +950,21 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * 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. - */ - var __values$3 = (this && this.__values) || function(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."); - }; + */ /** Combines multiple propagators into a single propagator. */ - var CompositePropagator = /** @class */ (function () { + class CompositePropagator { /** * Construct a composite propagator from a list of propagators. * * @param [config] Configuration object for composite propagator */ - function CompositePropagator(config) { - if (config === void 0) { config = {}; } + constructor(config = {}) { var _a; this._propagators = (_a = config.propagators) !== null && _a !== void 0 ? _a : []; this._fields = Array.from(new Set(this._propagators // older propagators may not have fields function, null check to be sure - .map(function (p) { return (typeof p.fields === 'function' ? p.fields() : []); }) - .reduce(function (x, y) { return x.concat(y); }, []))); + .map(p => (typeof p.fields === 'function' ? p.fields() : [])) + .reduce((x, y) => x.concat(y), []))); } /** * Run each of the configured propagators with the given context and carrier. @@ -5743,27 +975,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param context Context to inject * @param carrier Carrier into which context will be injected */ - CompositePropagator.prototype.inject = function (context, carrier, setter) { - var e_1, _a; - try { - for (var _b = __values$3(this._propagators), _c = _b.next(); !_c.done; _c = _b.next()) { - var propagator = _c.value; - try { - propagator.inject(context, carrier, setter); - } - catch (err) { - index.src.diag.warn("Failed to inject with " + propagator.constructor.name + ". Err: " + err.message); - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { + inject(context, carrier, setter) { + for (const propagator of this._propagators) { try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + propagator.inject(context, carrier, setter); + } + catch (err) { + traceApi.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`); } - finally { if (e_1) throw e_1.error; } } - }; + } /** * Run each of the configured propagators with the given context and carrier. * Propagators are run in the order they are configured, so if multiple @@ -5773,23 +994,22 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param context Context to add values to * @param carrier Carrier from which to extract context */ - CompositePropagator.prototype.extract = function (context, carrier, getter) { - return this._propagators.reduce(function (ctx, propagator) { + extract(context, carrier, getter) { + return this._propagators.reduce((ctx, propagator) => { try { return propagator.extract(ctx, carrier, getter); } catch (err) { - index.src.diag.warn("Failed to extract with " + propagator.constructor.name + ". Err: " + err.message); + traceApi.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`); } return ctx; }, context); - }; - CompositePropagator.prototype.fields = function () { + } + fields() { // return a new array so our fields cannot be modified return this._fields.slice(); - }; - return CompositePropagator; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -5806,12 +1026,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; - var VALID_KEY = "[a-z]" + VALID_KEY_CHAR_RANGE + "{0,255}"; - var VALID_VENDOR_KEY = "[a-z0-9]" + VALID_KEY_CHAR_RANGE + "{0,240}@[a-z]" + VALID_KEY_CHAR_RANGE + "{0,13}"; - var VALID_KEY_REGEX = new RegExp("^(?:" + VALID_KEY + "|" + VALID_VENDOR_KEY + ")$"); - var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; - var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; + const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; + const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; + const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; + const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); + const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; /** * Key is opaque string up to 256 characters printable. It MUST begin with a * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, @@ -5847,10 +1067,10 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var MAX_TRACE_STATE_ITEMS = 32; - var MAX_TRACE_STATE_LEN = 512; - var LIST_MEMBERS_SEPARATOR = ','; - var LIST_MEMBER_KEY_VALUE_SPLITTER = '='; + const MAX_TRACE_STATE_ITEMS = 32; + const MAX_TRACE_STATE_LEN = 512; + const LIST_MEMBERS_SEPARATOR = ','; + const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; /** * TraceState must be a class and not a simple object type because of the spec * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). @@ -5860,51 +1080,50 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * - The value of any key can be updated. Modified keys MUST be moved to the * beginning of the list. */ - var TraceState = /** @class */ (function () { - function TraceState(rawTraceState) { + class TraceState { + constructor(rawTraceState) { this._internalState = new Map(); if (rawTraceState) this._parse(rawTraceState); } - TraceState.prototype.set = function (key, value) { + set(key, value) { // TODO: Benchmark the different approaches(map vs list) and // use the faster one. - var traceState = this._clone(); + const traceState = this._clone(); if (traceState._internalState.has(key)) { traceState._internalState.delete(key); } traceState._internalState.set(key, value); return traceState; - }; - TraceState.prototype.unset = function (key) { - var traceState = this._clone(); + } + unset(key) { + const traceState = this._clone(); traceState._internalState.delete(key); return traceState; - }; - TraceState.prototype.get = function (key) { + } + get(key) { return this._internalState.get(key); - }; - TraceState.prototype.serialize = function () { - var _this = this; + } + serialize() { return this._keys() - .reduce(function (agg, key) { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + _this.get(key)); + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); return agg; }, []) .join(LIST_MEMBERS_SEPARATOR); - }; - TraceState.prototype._parse = function (rawTraceState) { + } + _parse(rawTraceState) { if (rawTraceState.length > MAX_TRACE_STATE_LEN) return; this._internalState = rawTraceState .split(LIST_MEMBERS_SEPARATOR) .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce(function (agg, part) { - var listMember = part.trim(); // Optional Whitespace (OWS) handling - var i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); if (i !== -1) { - var key = listMember.slice(0, i); - var value = listMember.slice(i + 1, part.length); + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); if (validateKey(key) && validateValue(value)) { agg.set(key, value); } @@ -5917,17 +1136,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function .reverse() // Use reverse same as original tracestate parse chain .slice(0, MAX_TRACE_STATE_ITEMS)); } - }; - TraceState.prototype._keys = function () { + } + _keys() { return Array.from(this._internalState.keys()).reverse(); - }; - TraceState.prototype._clone = function () { - var traceState = new TraceState(); + } + _clone() { + const traceState = new TraceState(); traceState._internalState = new Map(this._internalState); return traceState; - }; - return TraceState; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -5944,14 +1162,14 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var TRACE_PARENT_HEADER = 'traceparent'; - var TRACE_STATE_HEADER = 'tracestate'; - var VERSION = '00'; - var VERSION_PART = '(?!ff)[\\da-f]{2}'; - var TRACE_ID_PART = '(?![0]{32})[\\da-f]{32}'; - var PARENT_ID_PART = '(?![0]{16})[\\da-f]{16}'; - var FLAGS_PART = '[\\da-f]{2}'; - var TRACE_PARENT_REGEX = new RegExp("^\\s?(" + VERSION_PART + ")-(" + TRACE_ID_PART + ")-(" + PARENT_ID_PART + ")-(" + FLAGS_PART + ")(-.*)?\\s?$"); + const TRACE_PARENT_HEADER = 'traceparent'; + const TRACE_STATE_HEADER = 'tracestate'; + const VERSION = '00'; + const VERSION_PART = '(?!ff)[\\da-f]{2}'; + const TRACE_ID_PART = '(?![0]{32})[\\da-f]{32}'; + const PARENT_ID_PART = '(?![0]{16})[\\da-f]{16}'; + const FLAGS_PART = '[\\da-f]{2}'; + const TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`); /** * Parses information from the [traceparent] span tag and converts it into {@link SpanContext} * @param traceParent - A meta property that comes from server. @@ -5963,7 +1181,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * For more information see {@link https://www.w3.org/TR/trace-context/} */ function parseTraceParent(traceParent) { - var match = TRACE_PARENT_REGEX.exec(traceParent); + const match = TRACE_PARENT_REGEX.exec(traceParent); if (!match) return null; // According to the specification the implementation should be compatible @@ -5983,50 +1201,47 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Based on the Trace Context specification: * https://www.w3.org/TR/trace-context/ */ - var W3CTraceContextPropagator = /** @class */ (function () { - function W3CTraceContextPropagator() { - } - W3CTraceContextPropagator.prototype.inject = function (context, carrier, setter) { - var spanContext = index.src.trace.getSpanContext(context); + class W3CTraceContextPropagator { + inject(context, carrier, setter) { + const spanContext = traceApi.trace.getSpanContext(context); if (!spanContext || isTracingSuppressed(context) || - !index.src.isSpanContextValid(spanContext)) + !traceApi.isSpanContextValid(spanContext)) return; - var traceParent = VERSION + "-" + spanContext.traceId + "-" + spanContext.spanId + "-0" + Number(spanContext.traceFlags || index.src.TraceFlags.NONE).toString(16); + const traceParent = `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || traceApi.TraceFlags.NONE).toString(16)}`; setter.set(carrier, TRACE_PARENT_HEADER, traceParent); if (spanContext.traceState) { setter.set(carrier, TRACE_STATE_HEADER, spanContext.traceState.serialize()); } - }; - W3CTraceContextPropagator.prototype.extract = function (context, carrier, getter) { - var traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER); + } + extract(context, carrier, getter) { + const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER); if (!traceParentHeader) return context; - var traceParent = Array.isArray(traceParentHeader) + const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader; if (typeof traceParent !== 'string') return context; - var spanContext = parseTraceParent(traceParent); + const spanContext = parseTraceParent(traceParent); if (!spanContext) return context; spanContext.isRemote = true; - var traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER); + const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER); if (traceStateHeader) { // If more than one `tracestate` header is found, we merge them into a // single header. - var state = Array.isArray(traceStateHeader) + const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(',') : traceStateHeader; spanContext.traceState = new TraceState(typeof state === 'string' ? state : undefined); } - return index.src.trace.setSpanContext(context, spanContext); - }; - W3CTraceContextPropagator.prototype.fields = function () { + return traceApi.trace.setSpanContext(context, spanContext); + } + fields() { return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER]; - }; - return W3CTraceContextPropagator; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -6043,7 +1258,6 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - index.src.createContextKey('OpenTelemetry SDK Context Key RPC_METADATA'); var RPCType; (function (RPCType) { RPCType["HTTP"] = "http"; @@ -6069,17 +1283,17 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * based on lodash in order to support esm builds without esModuleInterop. * lodash is using MIT License. **/ - var objectTag = '[object Object]'; - var nullTag = '[object Null]'; - var undefinedTag = '[object Undefined]'; - var funcProto = Function.prototype; - var funcToString = funcProto.toString; - var objectCtorString = funcToString.call(Object); - var getPrototype = overArg(Object.getPrototypeOf, Object); - var objectProto = Object.prototype; - var hasOwnProperty = objectProto.hasOwnProperty; - var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - var nativeObjectToString = objectProto.toString; + const objectTag = '[object Object]'; + const nullTag = '[object Null]'; + const undefinedTag = '[object Undefined]'; + const funcProto = Function.prototype; + const funcToString = funcProto.toString; + const objectCtorString = funcToString.call(Object); + const getPrototype = overArg(Object.getPrototypeOf, Object); + const objectProto = Object.prototype; + const hasOwnProperty = objectProto.hasOwnProperty; + const symToStringTag = Symbol ? Symbol.toStringTag : undefined; + const nativeObjectToString = objectProto.toString; /** * Creates a unary function that invokes `func` with its argument transformed. * @@ -6125,11 +1339,11 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function if (!isObjectLike(value) || baseGetTag(value) !== objectTag) { return false; } - var proto = getPrototype(value); + const proto = getPrototype(value); if (proto === null) { return true; } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString); @@ -6184,8 +1398,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; - var unmasked = false; + const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + let unmasked = false; try { value[symToStringTag] = undefined; unmasked = true; @@ -6193,7 +1407,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function catch (e) { // silence } - var result = nativeObjectToString.call(value); + const result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; @@ -6231,18 +1445,14 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ /* eslint-disable @typescript-eslint/no-explicit-any */ - var MAX_LEVEL = 20; + const MAX_LEVEL = 20; /** * Merges objects together * @param args - objects / values to be merged */ - function merge() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = args.shift(); - var objects = new WeakMap(); + function merge(...args) { + let result = args.shift(); + const objects = new WeakMap(); while (args.length > 0) { result = mergeTwoObjects(result, args.shift(), 0, objects); } @@ -6262,9 +1472,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param objects - objects holder that has been already referenced - to prevent * cyclic dependency */ - function mergeTwoObjects(one, two, level, objects) { - if (level === void 0) { level = 0; } - var result; + function mergeTwoObjects(one, two, level = 0, objects) { + let result; if (level > MAX_LEVEL) { return undefined; } @@ -6275,14 +1484,14 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function else if (isArray(one)) { result = one.slice(); if (isArray(two)) { - for (var i = 0, j = two.length; i < j; i++) { + for (let i = 0, j = two.length; i < j; i++) { result.push(takeValue(two[i])); } } else if (isObject(two)) { - var keys = Object.keys(two); - for (var i = 0, j = keys.length; i < j; i++) { - var key = keys[i]; + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; result[key] = takeValue(two[key]); } } @@ -6293,10 +1502,10 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return two; } result = Object.assign({}, one); - var keys = Object.keys(two); - for (var i = 0, j = keys.length; i < j; i++) { - var key = keys[i]; - var twoValue = two[key]; + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + const twoValue = two[key]; if (isPrimitive(twoValue)) { if (typeof twoValue === 'undefined') { delete result[key]; @@ -6307,18 +1516,18 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } } else { - var obj1 = result[key]; - var obj2 = twoValue; + const obj1 = result[key]; + const obj2 = twoValue; if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) { delete result[key]; } else { if (isObject(obj1) && isObject(obj2)) { - var arr1 = objects.get(obj1) || []; - var arr2 = objects.get(obj2) || []; - arr1.push({ obj: one, key: key }); - arr2.push({ obj: two, key: key }); + const arr1 = objects.get(obj1) || []; + const arr2 = objects.get(obj2) || []; + arr1.push({ obj: one, key }); + arr2.push({ obj: two, key }); objects.set(obj1, arr1); objects.set(obj2, arr2); } @@ -6340,9 +1549,9 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param objects */ function wasObjectReferenced(obj, key, objects) { - var arr = objects.get(obj[key]) || []; - for (var i = 0, j = arr.length; i < j; i++) { - var info = arr[i]; + const arr = objects.get(obj[key]) || []; + for (let i = 0, j = arr.length; i < j; i++) { + const info = arr[i]; if (info.key === key && info.obj === obj) { return true; } @@ -6377,62 +1586,6 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return true; } - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var __extends$2 = (this && this.__extends) || (function () { - 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); - }; - return function (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 __()); - }; - })(); - /** - * Error that is thrown on timeouts. - */ - /** @class */ ((function (_super) { - __extends$2(TimeoutError, _super); - function TimeoutError(message) { - var _this = _super.call(this, message) || this; - // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see: - // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work - Object.setPrototypeOf(_this, TimeoutError.prototype); - return _this; - } - return TimeoutError; - })(Error)); - - (this && this.__values) || function(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."); - }; /* * Copyright The OpenTelemetry Authors * @@ -6472,29 +1625,23 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var Deferred = /** @class */ (function () { - function Deferred() { - var _this = this; - this._promise = new Promise(function (resolve, reject) { - _this._resolve = resolve; - _this._reject = reject; + class Deferred { + constructor() { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; }); } - Object.defineProperty(Deferred.prototype, "promise", { - get: function () { - return this._promise; - }, - enumerable: false, - configurable: true - }); - Deferred.prototype.resolve = function (val) { + get promise() { + return this._promise; + } + resolve(val) { this._resolve(val); - }; - Deferred.prototype.reject = function (err) { + } + reject(err) { this._reject(err); - }; - return Deferred; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -6511,75 +1658,35 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __read$4 = (this && this.__read) || function (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; - }; - var __spreadArray$3 = (this && this.__spreadArray) || function (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)); - }; /** * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked. */ - var BindOnceFuture = /** @class */ (function () { - function BindOnceFuture(_callback, _that) { + class BindOnceFuture { + constructor(_callback, _that) { this._callback = _callback; this._that = _that; this._isCalled = false; this._deferred = new Deferred(); } - Object.defineProperty(BindOnceFuture.prototype, "isCalled", { - get: function () { - return this._isCalled; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BindOnceFuture.prototype, "promise", { - get: function () { - return this._deferred.promise; - }, - enumerable: false, - configurable: true - }); - BindOnceFuture.prototype.call = function () { - var _a; - var _this = this; - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + get isCalled() { + return this._isCalled; + } + get promise() { + return this._deferred.promise; + } + call(...args) { if (!this._isCalled) { this._isCalled = true; try { - Promise.resolve((_a = this._callback).call.apply(_a, __spreadArray$3([this._that], __read$4(args), false))).then(function (val) { return _this._deferred.resolve(val); }, function (err) { return _this._deferred.reject(err); }); + Promise.resolve(this._callback.call(this._that, ...args)).then(val => this._deferred.resolve(val), err => this._deferred.reject(err)); } catch (err) { this._deferred.reject(err); } } return this._deferred.promise; - }; - return BindOnceFuture; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -6601,10 +1708,10 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Shared functionality used by Exporters while exporting data, including suppression of Traces. */ function _export(exporter, arg) { - return new Promise(function (resolve) { + return new Promise(resolve => { // prevent downstream exporter calls from generating spans - index.src.context.with(suppressTracing(index.src.context.active()), function () { - exporter.export(arg, function (result) { + traceApi.context.with(suppressTracing(traceApi.context.active()), () => { + exporter.export(arg, (result) => { resolve(result); }); }); @@ -6626,8 +1733,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var internal = { - _export: _export, + const internal = { + _export, }; /* @@ -6646,7 +1753,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ // Event name definitions - var ExceptionEventName = 'exception'; + const ExceptionEventName = 'exception'; /* * Copyright The OpenTelemetry Authors @@ -6663,65 +1770,17 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __assign$2 = (this && this.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - var __values$2 = (this && this.__values) || function(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."); - }; - var __read$3 = (this && this.__read) || function (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; - }; - var __spreadArray$2 = (this && this.__spreadArray) || function (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)); - }; /** * This class represents a span. */ - var Span = /** @class */ (function () { + class Span { /** * Constructs a new Span instance. * * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan. * */ - function Span(parentTracer, context, spanName, spanContext, kind, parentSpanId, links, startTime, _deprecatedClock, // keeping this argument even though it is unused to ensure backwards compatibility + constructor(parentTracer, context, spanName, spanContext, kind, parentSpanId, links = [], startTime, _deprecatedClock, // keeping this argument even though it is unused to ensure backwards compatibility attributes) { - if (links === void 0) { links = []; } this.attributes = {}; this.links = []; this.events = []; @@ -6729,7 +1788,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function this._droppedEventsCount = 0; this._droppedLinksCount = 0; this.status = { - code: index.src.SpanStatusCode.UNSET, + code: traceApi.SpanStatusCode.UNSET, }; this.endTime = [0, 0]; this._ended = false; @@ -6739,7 +1798,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function this.parentSpanId = parentSpanId; this.kind = kind; this.links = links; - var now = Date.now(); + const now = Date.now(); this._performanceStartTime = otperformance.now(); this._performanceOffset = now - (this._performanceStartTime + getTimeOrigin()); @@ -6756,18 +1815,18 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function this._spanProcessor = parentTracer.getActiveSpanProcessor(); this._spanProcessor.onStart(this, context); } - Span.prototype.spanContext = function () { + spanContext() { return this._spanContext; - }; - Span.prototype.setAttribute = function (key, value) { + } + setAttribute(key, value) { if (value == null || this._isSpanEnded()) return this; if (key.length === 0) { - index.src.diag.warn("Invalid attribute key: " + key); + traceApi.diag.warn(`Invalid attribute key: ${key}`); return this; } if (!isAttributeValue(value)) { - index.src.diag.warn("Invalid attribute value set for key: " + key); + traceApi.diag.warn(`Invalid attribute value set for key: ${key}`); return this; } if (Object.keys(this.attributes).length >= @@ -6778,24 +1837,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } this.attributes[key] = this._truncateToSize(value); return this; - }; - Span.prototype.setAttributes = function (attributes) { - var e_1, _a; - try { - for (var _b = __values$2(Object.entries(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) { - var _d = __read$3(_c.value, 2), k = _d[0], v = _d[1]; - this.setAttribute(k, v); - } - } - 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; } + } + setAttributes(attributes) { + for (const [k, v] of Object.entries(attributes)) { + this.setAttribute(k, v); } return this; - }; + } /** * * @param name Span Name @@ -6803,17 +1851,17 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * if type is {@type TimeInput} and 3rd param is undefined * @param [timeStamp] Specified time stamp for the event */ - Span.prototype.addEvent = function (name, attributesOrStartTime, timeStamp) { + addEvent(name, attributesOrStartTime, timeStamp) { if (this._isSpanEnded()) return this; if (this._spanLimits.eventCountLimit === 0) { - index.src.diag.warn('No events allowed.'); + traceApi.diag.warn('No events allowed.'); this._droppedEventsCount++; return this; } if (this.events.length >= this._spanLimits.eventCountLimit) { if (this._droppedEventsCount === 0) { - index.src.diag.debug('Dropping extra events.'); + traceApi.diag.debug('Dropping extra events.'); } this.events.shift(); this._droppedEventsCount++; @@ -6824,63 +1872,62 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } attributesOrStartTime = undefined; } - var attributes = sanitizeAttributes(attributesOrStartTime); + const attributes = sanitizeAttributes(attributesOrStartTime); this.events.push({ - name: name, - attributes: attributes, + name, + attributes, time: this._getTime(timeStamp), droppedAttributesCount: 0, }); return this; - }; - Span.prototype.addLink = function (link) { + } + addLink(link) { this.links.push(link); return this; - }; - Span.prototype.addLinks = function (links) { - var _a; - (_a = this.links).push.apply(_a, __spreadArray$2([], __read$3(links), false)); + } + addLinks(links) { + this.links.push(...links); return this; - }; - Span.prototype.setStatus = function (status) { + } + setStatus(status) { if (this._isSpanEnded()) return this; - this.status = __assign$2({}, status); + this.status = Object.assign({}, status); // When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`, // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus() // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or // undefined to avoid an incorrect type causing issues downstream. if (this.status.message != null && typeof status.message !== 'string') { - index.src.diag.warn("Dropping invalid status.message of type '" + typeof status.message + "', expected 'string'"); + traceApi.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`); delete this.status.message; } return this; - }; - Span.prototype.updateName = function (name) { + } + updateName(name) { if (this._isSpanEnded()) return this; this.name = name; return this; - }; - Span.prototype.end = function (endTime) { + } + end(endTime) { if (this._isSpanEnded()) { - index.src.diag.error(this.name + " " + this._spanContext.traceId + "-" + this._spanContext.spanId + " - You can only call end() on a span once."); + traceApi.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`); return; } this._ended = true; this.endTime = this._getTime(endTime); this._duration = hrTimeDuration(this.startTime, this.endTime); if (this._duration[0] < 0) { - index.src.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime); + traceApi.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime); this.endTime = this.startTime.slice(); this._duration = [0, 0]; } if (this._droppedEventsCount > 0) { - index.src.diag.warn("Dropped " + this._droppedEventsCount + " events because eventCountLimit reached"); + traceApi.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`); } this._spanProcessor.onEnd(this); - }; - Span.prototype._getTime = function (inp) { + } + _getTime(inp) { if (typeof inp === 'number' && inp < otperformance.now()) { // must be a performance timestamp // apply correction and convert to hrtime @@ -6900,90 +1947,70 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function // we can't use duration to calculate event/end times return millisToHrTime(Date.now()); } - var msDuration = otperformance.now() - this._performanceStartTime; + const msDuration = otperformance.now() - this._performanceStartTime; return addHrTimes(this.startTime, millisToHrTime(msDuration)); - }; - Span.prototype.isRecording = function () { + } + isRecording() { return this._ended === false; - }; - Span.prototype.recordException = function (exception, time) { - var attributes = {}; + } + recordException(exception, time) { + const attributes = {}; if (typeof exception === 'string') { - attributes[src.SEMATTRS_EXCEPTION_MESSAGE] = exception; + attributes[SEMATTRS_EXCEPTION_MESSAGE] = exception; } else if (exception) { if (exception.code) { - attributes[src.SEMATTRS_EXCEPTION_TYPE] = exception.code.toString(); + attributes[SEMATTRS_EXCEPTION_TYPE] = exception.code.toString(); } else if (exception.name) { - attributes[src.SEMATTRS_EXCEPTION_TYPE] = exception.name; + attributes[SEMATTRS_EXCEPTION_TYPE] = exception.name; } if (exception.message) { - attributes[src.SEMATTRS_EXCEPTION_MESSAGE] = exception.message; + attributes[SEMATTRS_EXCEPTION_MESSAGE] = exception.message; } if (exception.stack) { - attributes[src.SEMATTRS_EXCEPTION_STACKTRACE] = exception.stack; + attributes[SEMATTRS_EXCEPTION_STACKTRACE] = exception.stack; } } // these are minimum requirements from spec - if (attributes[src.SEMATTRS_EXCEPTION_TYPE] || - attributes[src.SEMATTRS_EXCEPTION_MESSAGE]) { + if (attributes[SEMATTRS_EXCEPTION_TYPE] || + attributes[SEMATTRS_EXCEPTION_MESSAGE]) { this.addEvent(ExceptionEventName, attributes, time); } else { - index.src.diag.warn("Failed to record an exception " + exception); + traceApi.diag.warn(`Failed to record an exception ${exception}`); } - }; - Object.defineProperty(Span.prototype, "duration", { - get: function () { - return this._duration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Span.prototype, "ended", { - get: function () { - return this._ended; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Span.prototype, "droppedAttributesCount", { - get: function () { - return this._droppedAttributesCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Span.prototype, "droppedEventsCount", { - get: function () { - return this._droppedEventsCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Span.prototype, "droppedLinksCount", { - get: function () { - return this._droppedLinksCount; - }, - enumerable: false, - configurable: true - }); - Span.prototype._isSpanEnded = function () { + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } + _isSpanEnded() { if (this._ended) { - index.src.diag.warn("Can not execute the operation on ended Span {traceId: " + this._spanContext.traceId + ", spanId: " + this._spanContext.spanId + "}"); + traceApi.diag.warn(`Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`); } return this._ended; - }; + } // Utility function to truncate given value within size // for value type of string, will truncate to given limit // for type of non-string, will return same value - Span.prototype._truncateToLimitUtil = function (value, limit) { + _truncateToLimitUtil(value, limit) { if (value.length <= limit) { return value; } return value.substr(0, limit); - }; + } /** * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then * return string with truncated to {@code attributeValueLengthLimit} characters @@ -6996,13 +2023,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param value Attribute value * @returns truncated attribute value if required, otherwise same value */ - Span.prototype._truncateToSize = function (value) { - var _this = this; - var limit = this._attributeValueLengthLimit; + _truncateToSize(value) { + const limit = this._attributeValueLengthLimit; // Check limit if (limit <= 0) { // Negative values are invalid, so do not truncate - index.src.diag.warn("Attribute value limit must be positive, got " + limit); + traceApi.diag.warn(`Attribute value limit must be positive, got ${limit}`); return value; } // String @@ -7011,15 +2037,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } // Array of strings if (Array.isArray(value)) { - return value.map(function (val) { - return typeof val === 'string' ? _this._truncateToLimitUtil(val, limit) : val; - }); + return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val); } // Other types, no need to apply value length limit return value; - }; - return Span; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -7075,19 +2098,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ /** Sampler that samples no traces. */ - var AlwaysOffSampler = /** @class */ (function () { - function AlwaysOffSampler() { - } - AlwaysOffSampler.prototype.shouldSample = function () { + class AlwaysOffSampler { + shouldSample() { return { decision: exports.SamplingDecision.NOT_RECORD, }; - }; - AlwaysOffSampler.prototype.toString = function () { + } + toString() { return 'AlwaysOffSampler'; - }; - return AlwaysOffSampler; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -7105,19 +2125,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ /** Sampler that samples all traces. */ - var AlwaysOnSampler = /** @class */ (function () { - function AlwaysOnSampler() { - } - AlwaysOnSampler.prototype.shouldSample = function () { + class AlwaysOnSampler { + shouldSample() { return { decision: exports.SamplingDecision.RECORD_AND_SAMPLED, }; - }; - AlwaysOnSampler.prototype.toString = function () { + } + toString() { return 'AlwaysOnSampler'; - }; - return AlwaysOnSampler; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -7138,8 +2155,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * A composite sampler that either respects the parent span's sampling decision * or delegates to `delegateSampler` for root spans. */ - var ParentBasedSampler = /** @class */ (function () { - function ParentBasedSampler(config) { + class ParentBasedSampler { + constructor(config) { var _a, _b, _c, _d; this._root = config.root; if (!this._root) { @@ -7155,27 +2172,26 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function this._localParentNotSampled = (_d = config.localParentNotSampled) !== null && _d !== void 0 ? _d : new AlwaysOffSampler(); } - ParentBasedSampler.prototype.shouldSample = function (context, traceId, spanName, spanKind, attributes, links) { - var parentContext = index.src.trace.getSpanContext(context); - if (!parentContext || !index.src.isSpanContextValid(parentContext)) { + shouldSample(context, traceId, spanName, spanKind, attributes, links) { + const parentContext = traceApi.trace.getSpanContext(context); + if (!parentContext || !traceApi.isSpanContextValid(parentContext)) { return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links); } if (parentContext.isRemote) { - if (parentContext.traceFlags & index.src.TraceFlags.SAMPLED) { + if (parentContext.traceFlags & traceApi.TraceFlags.SAMPLED) { return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); } return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); } - if (parentContext.traceFlags & index.src.TraceFlags.SAMPLED) { + if (parentContext.traceFlags & traceApi.TraceFlags.SAMPLED) { return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); } return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); - }; - ParentBasedSampler.prototype.toString = function () { - return "ParentBased{root=" + this._root.toString() + ", remoteParentSampled=" + this._remoteParentSampled.toString() + ", remoteParentNotSampled=" + this._remoteParentNotSampled.toString() + ", localParentSampled=" + this._localParentSampled.toString() + ", localParentNotSampled=" + this._localParentNotSampled.toString() + "}"; - }; - return ParentBasedSampler; - }()); + } + toString() { + return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`; + } + } /* * Copyright The OpenTelemetry Authors @@ -7193,39 +2209,37 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ /** Sampler that samples a given fraction of traces based of trace id deterministically. */ - var TraceIdRatioBasedSampler = /** @class */ (function () { - function TraceIdRatioBasedSampler(_ratio) { - if (_ratio === void 0) { _ratio = 0; } + class TraceIdRatioBasedSampler { + constructor(_ratio = 0) { this._ratio = _ratio; this._ratio = this._normalize(_ratio); this._upperBound = Math.floor(this._ratio * 0xffffffff); } - TraceIdRatioBasedSampler.prototype.shouldSample = function (context, traceId) { + shouldSample(context, traceId) { return { - decision: index.src.isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound + decision: traceApi.isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound ? exports.SamplingDecision.RECORD_AND_SAMPLED : exports.SamplingDecision.NOT_RECORD, }; - }; - TraceIdRatioBasedSampler.prototype.toString = function () { - return "TraceIdRatioBased{" + this._ratio + "}"; - }; - TraceIdRatioBasedSampler.prototype._normalize = function (ratio) { + } + toString() { + return `TraceIdRatioBased{${this._ratio}}`; + } + _normalize(ratio) { if (typeof ratio !== 'number' || isNaN(ratio)) return 0; return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio; - }; - TraceIdRatioBasedSampler.prototype._accumulate = function (traceId) { - var accumulation = 0; - for (var i = 0; i < traceId.length / 8; i++) { - var pos = i * 8; - var part = parseInt(traceId.slice(pos, pos + 8), 16); + } + _accumulate(traceId) { + let accumulation = 0; + for (let i = 0; i < traceId.length / 8; i++) { + const pos = i * 8; + const part = parseInt(traceId.slice(pos, pos + 8), 16); accumulation = (accumulation ^ part) >>> 0; } return accumulation; - }; - return TraceIdRatioBasedSampler; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -7242,9 +2256,9 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var env = getEnv(); - var FALLBACK_OTEL_TRACES_SAMPLER = TracesSamplerValues.AlwaysOn; - var DEFAULT_RATIO = 1; + const env = getEnv(); + const FALLBACK_OTEL_TRACES_SAMPLER = TracesSamplerValues.AlwaysOn; + const DEFAULT_RATIO = 1; /** * Load default configuration. For fields with primitive values, any user-provided * value will override the corresponding default value. For fields with @@ -7254,7 +2268,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function // object needs to be wrapped in this function and called when needed otherwise // envs are parsed before tests are ran - causes tests using these envs to fail function loadDefaultConfig() { - var _env = getEnv(); + const _env = getEnv(); return { sampler: buildSamplerFromEnv(env), forceFlushTimeoutMillis: 30000, @@ -7276,8 +2290,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Based on environment, builds a sampler, complies with specification. * @param environment optional, by default uses getEnv(), but allows passing a value to reuse parsed environment */ - function buildSamplerFromEnv(environment) { - if (environment === void 0) { environment = getEnv(); } + function buildSamplerFromEnv(environment = getEnv()) { switch (environment.OTEL_TRACES_SAMPLER) { case TracesSamplerValues.AlwaysOn: return new AlwaysOnSampler(); @@ -7298,23 +2311,23 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment)), }); default: - index.src.diag.error("OTEL_TRACES_SAMPLER value \"" + environment.OTEL_TRACES_SAMPLER + " invalid, defaulting to " + FALLBACK_OTEL_TRACES_SAMPLER + "\"."); + traceApi.diag.error(`OTEL_TRACES_SAMPLER value "${environment.OTEL_TRACES_SAMPLER} invalid, defaulting to ${FALLBACK_OTEL_TRACES_SAMPLER}".`); return new AlwaysOnSampler(); } } function getSamplerProbabilityFromEnv(environment) { if (environment.OTEL_TRACES_SAMPLER_ARG === undefined || environment.OTEL_TRACES_SAMPLER_ARG === '') { - index.src.diag.error("OTEL_TRACES_SAMPLER_ARG is blank, defaulting to " + DEFAULT_RATIO + "."); + traceApi.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`); return DEFAULT_RATIO; } - var probability = Number(environment.OTEL_TRACES_SAMPLER_ARG); + const probability = Number(environment.OTEL_TRACES_SAMPLER_ARG); if (isNaN(probability)) { - index.src.diag.error("OTEL_TRACES_SAMPLER_ARG=" + environment.OTEL_TRACES_SAMPLER_ARG + " was given, but it is invalid, defaulting to " + DEFAULT_RATIO + "."); + traceApi.diag.error(`OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${DEFAULT_RATIO}.`); return DEFAULT_RATIO; } if (probability < 0 || probability > 1) { - index.src.diag.error("OTEL_TRACES_SAMPLER_ARG=" + environment.OTEL_TRACES_SAMPLER_ARG + " was given, but it is out of range ([0..1]), defaulting to " + DEFAULT_RATIO + "."); + traceApi.diag.error(`OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`); return DEFAULT_RATIO; } return probability; @@ -7340,11 +2353,11 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * user provided configurations. */ function mergeConfig(userConfig) { - var perInstanceDefaults = { + const perInstanceDefaults = { sampler: buildSamplerFromEnv(), }; - var DEFAULT_CONFIG = loadDefaultConfig(); - var target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig); + const DEFAULT_CONFIG = loadDefaultConfig(); + const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig); target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {}); target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {}); return target; @@ -7356,8 +2369,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function */ function reconfigureLimits(userConfig) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; - var spanLimits = Object.assign({}, userConfig.spanLimits); - var parsedEnvConfig = getEnvWithoutDefaults(); + const spanLimits = Object.assign({}, userConfig.spanLimits); + const parsedEnvConfig = getEnvWithoutDefaults(); /** * Reassign span attribute count limit to use first non null value defined by user or use default value */ @@ -7368,7 +2381,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function */ spanLimits.attributeValueLengthLimit = (_m = (_l = (_k = (_h = (_g = userConfig.spanLimits) === null || _g === void 0 ? void 0 : _g.attributeValueLengthLimit) !== null && _h !== void 0 ? _h : (_j = userConfig.generalLimits) === null || _j === void 0 ? void 0 : _j.attributeValueLengthLimit) !== null && _k !== void 0 ? _k : parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) !== null && _l !== void 0 ? _l : parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT) !== null && _m !== void 0 ? _m : DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT; - return Object.assign({}, userConfig, { spanLimits: spanLimits }); + return Object.assign({}, userConfig, { spanLimits }); } /* @@ -7390,13 +2403,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Implementation of the {@link SpanProcessor} that batches spans exported by * the SDK then pushes them to the exporter pipeline. */ - var BatchSpanProcessorBase = /** @class */ (function () { - function BatchSpanProcessorBase(_exporter, config) { + class BatchSpanProcessorBase { + constructor(_exporter, config) { this._exporter = _exporter; this._isExporting = false; this._finishedSpans = []; this._droppedSpansCount = 0; - var env = getEnv(); + const env = getEnv(); this._maxExportBatchSize = typeof (config === null || config === void 0 ? void 0 : config.maxExportBatchSize) === 'number' ? config.maxExportBatchSize @@ -7415,121 +2428,116 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function : env.OTEL_BSP_EXPORT_TIMEOUT; this._shutdownOnce = new BindOnceFuture(this._shutdown, this); if (this._maxExportBatchSize > this._maxQueueSize) { - index.src.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'); + traceApi.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'); this._maxExportBatchSize = this._maxQueueSize; } } - BatchSpanProcessorBase.prototype.forceFlush = function () { + forceFlush() { if (this._shutdownOnce.isCalled) { return this._shutdownOnce.promise; } return this._flushAll(); - }; + } // does nothing. - BatchSpanProcessorBase.prototype.onStart = function (_span, _parentContext) { }; - BatchSpanProcessorBase.prototype.onEnd = function (span) { + onStart(_span, _parentContext) { } + onEnd(span) { if (this._shutdownOnce.isCalled) { return; } - if ((span.spanContext().traceFlags & index.src.TraceFlags.SAMPLED) === 0) { + if ((span.spanContext().traceFlags & traceApi.TraceFlags.SAMPLED) === 0) { return; } this._addToBuffer(span); - }; - BatchSpanProcessorBase.prototype.shutdown = function () { + } + shutdown() { return this._shutdownOnce.call(); - }; - BatchSpanProcessorBase.prototype._shutdown = function () { - var _this = this; + } + _shutdown() { return Promise.resolve() - .then(function () { - return _this.onShutdown(); + .then(() => { + return this.onShutdown(); }) - .then(function () { - return _this._flushAll(); + .then(() => { + return this._flushAll(); }) - .then(function () { - return _this._exporter.shutdown(); + .then(() => { + return this._exporter.shutdown(); }); - }; + } /** Add a span in the buffer. */ - BatchSpanProcessorBase.prototype._addToBuffer = function (span) { + _addToBuffer(span) { if (this._finishedSpans.length >= this._maxQueueSize) { // limit reached, drop span if (this._droppedSpansCount === 0) { - index.src.diag.debug('maxQueueSize reached, dropping spans'); + traceApi.diag.debug('maxQueueSize reached, dropping spans'); } this._droppedSpansCount++; return; } if (this._droppedSpansCount > 0) { // some spans were dropped, log once with count of spans dropped - index.src.diag.warn("Dropped " + this._droppedSpansCount + " spans because maxQueueSize reached"); + traceApi.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`); this._droppedSpansCount = 0; } this._finishedSpans.push(span); this._maybeStartTimer(); - }; + } /** * Send all spans to the exporter respecting the batch size limit * This function is used only on forceFlush or shutdown, * for all other cases _flush should be used * */ - BatchSpanProcessorBase.prototype._flushAll = function () { - var _this = this; - return new Promise(function (resolve, reject) { - var promises = []; + _flushAll() { + return new Promise((resolve, reject) => { + const promises = []; // calculate number of batches - var count = Math.ceil(_this._finishedSpans.length / _this._maxExportBatchSize); - for (var i = 0, j = count; i < j; i++) { - promises.push(_this._flushOneBatch()); + const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize); + for (let i = 0, j = count; i < j; i++) { + promises.push(this._flushOneBatch()); } Promise.all(promises) - .then(function () { + .then(() => { resolve(); }) .catch(reject); }); - }; - BatchSpanProcessorBase.prototype._flushOneBatch = function () { - var _this = this; + } + _flushOneBatch() { this._clearTimer(); if (this._finishedSpans.length === 0) { return Promise.resolve(); } - return new Promise(function (resolve, reject) { - var timer = setTimeout(function () { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { // don't wait anymore for export, this way the next batch can start reject(new Error('Timeout')); - }, _this._exportTimeoutMillis); + }, this._exportTimeoutMillis); // prevent downstream exporter calls from generating spans - index.src.context.with(suppressTracing(index.src.context.active()), function () { + traceApi.context.with(suppressTracing(traceApi.context.active()), () => { // Reset the finished spans buffer here because the next invocations of the _flush method // could pass the same finished spans to the exporter if the buffer is cleared // outside the execution of this callback. - var spans; - if (_this._finishedSpans.length <= _this._maxExportBatchSize) { - spans = _this._finishedSpans; - _this._finishedSpans = []; + let spans; + if (this._finishedSpans.length <= this._maxExportBatchSize) { + spans = this._finishedSpans; + this._finishedSpans = []; } else { - spans = _this._finishedSpans.splice(0, _this._maxExportBatchSize); + spans = this._finishedSpans.splice(0, this._maxExportBatchSize); } - var doExport = function () { - return _this._exporter.export(spans, function (result) { - var _a; - clearTimeout(timer); - if (result.code === ExportResultCode.SUCCESS) { - resolve(); - } - else { - reject((_a = result.error) !== null && _a !== void 0 ? _a : new Error('BatchSpanProcessor: span export failed')); - } - }); - }; - var pendingResources = null; - for (var i = 0, len = spans.length; i < len; i++) { - var span = spans[i]; + const doExport = () => this._exporter.export(spans, result => { + var _a; + clearTimeout(timer); + if (result.code === ExportResultCode.SUCCESS) { + resolve(); + } + else { + reject((_a = result.error) !== null && _a !== void 0 ? _a : new Error('BatchSpanProcessor: span export failed')); + } + }); + let pendingResources = null; + for (let i = 0, len = spans.length; i < len; i++) { + const span = spans[i]; if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) { pendingResources !== null && pendingResources !== void 0 ? pendingResources : (pendingResources = []); @@ -7541,30 +2549,29 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function doExport(); } else { - Promise.all(pendingResources).then(doExport, function (err) { + Promise.all(pendingResources).then(doExport, err => { globalErrorHandler(err); reject(err); }); } }); }); - }; - BatchSpanProcessorBase.prototype._maybeStartTimer = function () { - var _this = this; + } + _maybeStartTimer() { if (this._isExporting) return; - var flush = function () { - _this._isExporting = true; - _this._flushOneBatch() - .finally(function () { - _this._isExporting = false; - if (_this._finishedSpans.length > 0) { - _this._clearTimer(); - _this._maybeStartTimer(); + const flush = () => { + this._isExporting = true; + this._flushOneBatch() + .finally(() => { + this._isExporting = false; + if (this._finishedSpans.length > 0) { + this._clearTimer(); + this._maybeStartTimer(); } }) - .catch(function (e) { - _this._isExporting = false; + .catch(e => { + this._isExporting = false; globalErrorHandler(e); }); }; @@ -7574,17 +2581,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } if (this._timer !== undefined) return; - this._timer = setTimeout(function () { return flush(); }, this._scheduledDelayMillis); + this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); unrefTimer(this._timer); - }; - BatchSpanProcessorBase.prototype._clearTimer = function () { + } + _clearTimer() { if (this._timer !== undefined) { clearTimeout(this._timer); this._timer = undefined; } - }; - return BatchSpanProcessorBase; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -7601,46 +2607,28 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __extends$1 = (this && this.__extends) || (function () { - 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); - }; - return function (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 __()); - }; - })(); - var BatchSpanProcessor = /** @class */ (function (_super) { - __extends$1(BatchSpanProcessor, _super); - function BatchSpanProcessor(_exporter, config) { - var _this = _super.call(this, _exporter, config) || this; - _this.onInit(config); - return _this; - } - BatchSpanProcessor.prototype.onInit = function (config) { - var _this = this; + class BatchSpanProcessor extends BatchSpanProcessorBase { + constructor(_exporter, config) { + super(_exporter, config); + this.onInit(config); + } + onInit(config) { if ((config === null || config === void 0 ? void 0 : config.disableAutoFlushOnDocumentHide) !== true && typeof document !== 'undefined') { - this._visibilityChangeListener = function () { + this._visibilityChangeListener = () => { if (document.visibilityState === 'hidden') { - void _this.forceFlush(); + void this.forceFlush(); } }; - this._pageHideListener = function () { - void _this.forceFlush(); + this._pageHideListener = () => { + void this.forceFlush(); }; document.addEventListener('visibilitychange', this._visibilityChangeListener); // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769 document.addEventListener('pagehide', this._pageHideListener); } - }; - BatchSpanProcessor.prototype.onShutdown = function () { + } + onShutdown() { if (typeof document !== 'undefined') { if (this._visibilityChangeListener) { document.removeEventListener('visibilitychange', this._visibilityChangeListener); @@ -7649,9 +2637,8 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function document.removeEventListener('pagehide', this._pageHideListener); } } - }; - return BatchSpanProcessor; - }(BatchSpanProcessorBase)); + } + } /* * Copyright The OpenTelemetry Authors @@ -7668,10 +2655,10 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var SPAN_ID_BYTES = 8; - var TRACE_ID_BYTES = 16; - var RandomIdGenerator = /** @class */ (function () { - function RandomIdGenerator() { + const SPAN_ID_BYTES = 8; + const TRACE_ID_BYTES = 16; + class RandomIdGenerator { + constructor() { /** * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex * characters corresponding to 128 bits. @@ -7683,12 +2670,11 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function */ this.generateSpanId = getIdGenerator(SPAN_ID_BYTES); } - return RandomIdGenerator; - }()); - var SHARED_CHAR_CODES_ARRAY = Array(32); + } + const SHARED_CHAR_CODES_ARRAY = Array(32); function getIdGenerator(bytes) { return function generateId() { - for (var i = 0; i < bytes * 2; i++) { + for (let i = 0; i < bytes * 2; i++) { SHARED_CHAR_CODES_ARRAY[i] = Math.floor(Math.random() * 16) + 48; // valid hex characters in the range 48-57 and 97-102 if (SHARED_CHAR_CODES_ARRAY[i] >= 58) { @@ -7717,13 +2703,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function /** * This class represents a basic tracer. */ - var Tracer = /** @class */ (function () { + class Tracer { /** * Constructs a new Tracer instance. */ - function Tracer(instrumentationLibrary, config, _tracerProvider) { + constructor(instrumentationLibrary, config, _tracerProvider) { this._tracerProvider = _tracerProvider; - var localConfig = mergeConfig(config); + const localConfig = mergeConfig(config); this._sampler = localConfig.sampler; this._generalLimits = localConfig.generalLimits; this._spanLimits = localConfig.spanLimits; @@ -7735,27 +2721,25 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * Starts a new Span or returns the default NoopSpan based on the sampling * decision. */ - Tracer.prototype.startSpan = function (name, options, context) { + startSpan(name, options = {}, context = traceApi.context.active()) { var _a, _b, _c; - if (options === void 0) { options = {}; } - if (context === void 0) { context = index.src.context.active(); } // remove span from context in case a root span is requested via options if (options.root) { - context = index.src.trace.deleteSpan(context); + context = traceApi.trace.deleteSpan(context); } - var parentSpan = index.src.trace.getSpan(context); + const parentSpan = traceApi.trace.getSpan(context); if (isTracingSuppressed(context)) { - index.src.diag.debug('Instrumentation suppressed, returning Noop Span'); - var nonRecordingSpan = index.src.trace.wrapSpanContext(index.src.INVALID_SPAN_CONTEXT); + traceApi.diag.debug('Instrumentation suppressed, returning Noop Span'); + const nonRecordingSpan = traceApi.trace.wrapSpanContext(traceApi.INVALID_SPAN_CONTEXT); return nonRecordingSpan; } - var parentSpanContext = parentSpan === null || parentSpan === void 0 ? void 0 : parentSpan.spanContext(); - var spanId = this._idGenerator.generateSpanId(); - var traceId; - var traceState; - var parentSpanId; + const parentSpanContext = parentSpan === null || parentSpan === void 0 ? void 0 : parentSpan.spanContext(); + const spanId = this._idGenerator.generateSpanId(); + let traceId; + let traceState; + let parentSpanId; if (!parentSpanContext || - !index.src.trace.isSpanContextValid(parentSpanContext)) { + !traceApi.trace.isSpanContextValid(parentSpanContext)) { // New root span. traceId = this._idGenerator.generateTraceId(); } @@ -7765,36 +2749,36 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function traceState = parentSpanContext.traceState; parentSpanId = parentSpanContext.spanId; } - var spanKind = (_a = options.kind) !== null && _a !== void 0 ? _a : index.src.SpanKind.INTERNAL; - var links = ((_b = options.links) !== null && _b !== void 0 ? _b : []).map(function (link) { + const spanKind = (_a = options.kind) !== null && _a !== void 0 ? _a : traceApi.SpanKind.INTERNAL; + const links = ((_b = options.links) !== null && _b !== void 0 ? _b : []).map(link => { return { context: link.context, attributes: sanitizeAttributes(link.attributes), }; }); - var attributes = sanitizeAttributes(options.attributes); + const attributes = sanitizeAttributes(options.attributes); // make sampling decision - var samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links); + const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links); traceState = (_c = samplingResult.traceState) !== null && _c !== void 0 ? _c : traceState; - var traceFlags = samplingResult.decision === index.src.SamplingDecision.RECORD_AND_SAMPLED - ? index.src.TraceFlags.SAMPLED - : index.src.TraceFlags.NONE; - var spanContext = { traceId: traceId, spanId: spanId, traceFlags: traceFlags, traceState: traceState }; - if (samplingResult.decision === index.src.SamplingDecision.NOT_RECORD) { - index.src.diag.debug('Recording is off, propagating context in a non-recording span'); - var nonRecordingSpan = index.src.trace.wrapSpanContext(spanContext); + const traceFlags = samplingResult.decision === traceApi.SamplingDecision.RECORD_AND_SAMPLED + ? traceApi.TraceFlags.SAMPLED + : traceApi.TraceFlags.NONE; + const spanContext = { traceId, spanId, traceFlags, traceState }; + if (samplingResult.decision === traceApi.SamplingDecision.NOT_RECORD) { + traceApi.diag.debug('Recording is off, propagating context in a non-recording span'); + const nonRecordingSpan = traceApi.trace.wrapSpanContext(spanContext); return nonRecordingSpan; } // Set initial span attributes. The attributes object may have been mutated // by the sampler, so we sanitize the merged attributes before setting them. - var initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes)); - var span = new Span(this, context, name, spanContext, spanKind, parentSpanId, links, options.startTime, undefined, initAttributes); + const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes)); + const span = new Span(this, context, name, spanContext, spanKind, parentSpanId, links, options.startTime, undefined, initAttributes); return span; - }; - Tracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { - var opts; - var ctx; - var fn; + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; if (arguments.length < 2) { return; } @@ -7810,24 +2794,23 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function ctx = arg3; fn = arg4; } - var parentContext = ctx !== null && ctx !== void 0 ? ctx : index.src.context.active(); - var span = this.startSpan(name, opts, parentContext); - var contextWithSpanSet = index.src.trace.setSpan(parentContext, span); - return index.src.context.with(contextWithSpanSet, fn, undefined, span); - }; + const parentContext = ctx !== null && ctx !== void 0 ? ctx : traceApi.context.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = traceApi.trace.setSpan(parentContext, span); + return traceApi.context.with(contextWithSpanSet, fn, undefined, span); + } /** Returns the active {@link GeneralLimits}. */ - Tracer.prototype.getGeneralLimits = function () { + getGeneralLimits() { return this._generalLimits; - }; + } /** Returns the active {@link SpanLimits}. */ - Tracer.prototype.getSpanLimits = function () { + getSpanLimits() { return this._spanLimits; - }; - Tracer.prototype.getActiveSpanProcessor = function () { + } + getActiveSpanProcessor() { return this._tracerProvider.getActiveSpanProcessor(); - }; - return Tracer; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -7855,153 +2838,74 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://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. - */ - var __assign$1 = (this && this.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$1 = (this && this.__awaiter) || function (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()); - }); - }; - var __generator$1 = (this && this.__generator) || function (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 }; - } - }; - var __read$2 = (this && this.__read) || function (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; - }; + * https://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. + */ /** * A Resource describes the entity for which a signals (metrics or trace) are * collected. */ - var Resource = /** @class */ (function () { - function Resource( + class Resource { + constructor( /** * A dictionary of attributes with string keys and values that provide * information about the entity as numbers, strings or booleans * TODO: Consider to add check/validation on attributes. */ attributes, asyncAttributesPromise) { - var _this = this; var _a; this._attributes = attributes; this.asyncAttributesPending = asyncAttributesPromise != null; this._syncAttributes = (_a = this._attributes) !== null && _a !== void 0 ? _a : {}; - this._asyncAttributesPromise = asyncAttributesPromise === null || asyncAttributesPromise === void 0 ? void 0 : asyncAttributesPromise.then(function (asyncAttributes) { - _this._attributes = Object.assign({}, _this._attributes, asyncAttributes); - _this.asyncAttributesPending = false; + this._asyncAttributesPromise = asyncAttributesPromise === null || asyncAttributesPromise === void 0 ? void 0 : asyncAttributesPromise.then(asyncAttributes => { + this._attributes = Object.assign({}, this._attributes, asyncAttributes); + this.asyncAttributesPending = false; return asyncAttributes; - }, function (err) { - index.src.diag.debug("a resource's async attributes promise rejected: %s", err); - _this.asyncAttributesPending = false; + }, err => { + traceApi.diag.debug("a resource's async attributes promise rejected: %s", err); + this.asyncAttributesPending = false; return {}; }); } /** * Returns an empty Resource */ - Resource.empty = function () { + static empty() { return Resource.EMPTY; - }; + } /** * Returns a Resource that identifies the SDK in use. */ - Resource.default = function () { + static default() { + return new Resource({ + [SEMRESATTRS_SERVICE_NAME]: defaultServiceName(), + [SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE], + [SEMRESATTRS_TELEMETRY_SDK_NAME]: SDK_INFO[SEMRESATTRS_TELEMETRY_SDK_NAME], + [SEMRESATTRS_TELEMETRY_SDK_VERSION]: SDK_INFO[SEMRESATTRS_TELEMETRY_SDK_VERSION], + }); + } + get attributes() { var _a; - return new Resource((_a = {}, - _a[src.SEMRESATTRS_SERVICE_NAME] = defaultServiceName(), - _a[src.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE] = SDK_INFO[src.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE], - _a[src.SEMRESATTRS_TELEMETRY_SDK_NAME] = SDK_INFO[src.SEMRESATTRS_TELEMETRY_SDK_NAME], - _a[src.SEMRESATTRS_TELEMETRY_SDK_VERSION] = SDK_INFO[src.SEMRESATTRS_TELEMETRY_SDK_VERSION], - _a)); - }; - Object.defineProperty(Resource.prototype, "attributes", { - get: function () { - var _a; - if (this.asyncAttributesPending) { - index.src.diag.error('Accessing resource attributes before async attributes settled'); - } - return (_a = this._attributes) !== null && _a !== void 0 ? _a : {}; - }, - enumerable: false, - configurable: true - }); + if (this.asyncAttributesPending) { + traceApi.diag.error('Accessing resource attributes before async attributes settled'); + } + return (_a = this._attributes) !== null && _a !== void 0 ? _a : {}; + } /** * Returns a promise that will never be rejected. Resolves when all async attributes have finished being added to * this Resource's attributes. This is useful in exporters to block until resource detection * has finished. */ - Resource.prototype.waitForAsyncAttributes = function () { - return __awaiter$1(this, void 0, void 0, function () { - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.asyncAttributesPending) return [3 /*break*/, 2]; - return [4 /*yield*/, this._asyncAttributesPromise]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; + async waitForAsyncAttributes() { + if (this.asyncAttributesPending) { + await this._asyncAttributesPromise; + } + } /** * Returns a new, merged {@link Resource} by merging the current Resource * with the other Resource. In case of a collision, other Resource takes @@ -8010,152 +2914,27 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param other the Resource that will be merged with this. * @returns the newly merged Resource. */ - Resource.prototype.merge = function (other) { - var _this = this; + merge(other) { var _a; if (!other) return this; // SpanAttributes from other resource overwrite attributes from this resource. - var mergedSyncAttributes = __assign$1(__assign$1({}, this._syncAttributes), ((_a = other._syncAttributes) !== null && _a !== void 0 ? _a : other.attributes)); + const mergedSyncAttributes = Object.assign(Object.assign({}, this._syncAttributes), ((_a = other._syncAttributes) !== null && _a !== void 0 ? _a : other.attributes)); if (!this._asyncAttributesPromise && !other._asyncAttributesPromise) { return new Resource(mergedSyncAttributes); } - var mergedAttributesPromise = Promise.all([ + const mergedAttributesPromise = Promise.all([ this._asyncAttributesPromise, other._asyncAttributesPromise, - ]).then(function (_a) { - var _b; - var _c = __read$2(_a, 2), thisAsyncAttributes = _c[0], otherAsyncAttributes = _c[1]; - return __assign$1(__assign$1(__assign$1(__assign$1({}, _this._syncAttributes), thisAsyncAttributes), ((_b = other._syncAttributes) !== null && _b !== void 0 ? _b : other.attributes)), otherAsyncAttributes); + ]).then(([thisAsyncAttributes, otherAsyncAttributes]) => { + var _a; + return Object.assign(Object.assign(Object.assign(Object.assign({}, this._syncAttributes), thisAsyncAttributes), ((_a = other._syncAttributes) !== null && _a !== void 0 ? _a : other.attributes)), otherAsyncAttributes); }); return new Resource(mergedSyncAttributes, mergedAttributesPromise); - }; - Resource.EMPTY = new Resource({}); - return Resource; - }()); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - (this && this.__values) || function(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."); - }; - (this && this.__read) || function (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; - }; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - (this && this.__awaiter) || function (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()); - }); - }; - (this && this.__generator) || function (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 }; } - }; + } + Resource.EMPTY = new Resource({}); /* * Copyright The OpenTelemetry Authors @@ -8172,108 +2951,52 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __values$1 = (this && this.__values) || function(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."); - }; /** * Implementation of the {@link SpanProcessor} that simply forwards all * received events to a list of {@link SpanProcessor}s. */ - var MultiSpanProcessor = /** @class */ (function () { - function MultiSpanProcessor(_spanProcessors) { + class MultiSpanProcessor { + constructor(_spanProcessors) { this._spanProcessors = _spanProcessors; } - MultiSpanProcessor.prototype.forceFlush = function () { - var e_1, _a; - var promises = []; - try { - for (var _b = __values$1(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) { - var spanProcessor = _c.value; - promises.push(spanProcessor.forceFlush()); - } - } - 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; } + forceFlush() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.forceFlush()); } - return new Promise(function (resolve) { + return new Promise(resolve => { Promise.all(promises) - .then(function () { + .then(() => { resolve(); }) - .catch(function (error) { + .catch(error => { globalErrorHandler(error || new Error('MultiSpanProcessor: forceFlush failed')); resolve(); }); }); - }; - MultiSpanProcessor.prototype.onStart = function (span, context) { - var e_2, _a; - try { - for (var _b = __values$1(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) { - var spanProcessor = _c.value; - spanProcessor.onStart(span, context); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_2) throw e_2.error; } - } - }; - MultiSpanProcessor.prototype.onEnd = function (span) { - var e_3, _a; - try { - for (var _b = __values$1(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) { - var spanProcessor = _c.value; - spanProcessor.onEnd(span); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_3) throw e_3.error; } + } + onStart(span, context) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onStart(span, context); } - }; - MultiSpanProcessor.prototype.shutdown = function () { - var e_4, _a; - var promises = []; - try { - for (var _b = __values$1(this._spanProcessors), _c = _b.next(); !_c.done; _c = _b.next()) { - var spanProcessor = _c.value; - promises.push(spanProcessor.shutdown()); - } + } + onEnd(span) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onEnd(span); } - catch (e_4_1) { e_4 = { error: e_4_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_4) throw e_4.error; } + } + shutdown() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.shutdown()); } - return new Promise(function (resolve, reject) { - Promise.all(promises).then(function () { + return new Promise((resolve, reject) => { + Promise.all(promises).then(() => { resolve(); }, reject); }); - }; - return MultiSpanProcessor; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -8291,19 +3014,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * limitations under the License. */ /** No-op implementation of SpanProcessor */ - var NoopSpanProcessor = /** @class */ (function () { - function NoopSpanProcessor() { - } - NoopSpanProcessor.prototype.onStart = function (_span, _context) { }; - NoopSpanProcessor.prototype.onEnd = function (_span) { }; - NoopSpanProcessor.prototype.shutdown = function () { + class NoopSpanProcessor { + onStart(_span, _context) { } + onEnd(_span) { } + shutdown() { return Promise.resolve(); - }; - NoopSpanProcessor.prototype.forceFlush = function () { + } + forceFlush() { return Promise.resolve(); - }; - return NoopSpanProcessor; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -8330,55 +3050,52 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function /** * This class represents a basic tracer provider which platform libraries can extend */ - var BasicTracerProvider = /** @class */ (function () { - function BasicTracerProvider(config) { - if (config === void 0) { config = {}; } + class BasicTracerProvider { + constructor(config = {}) { var _a; this._registeredSpanProcessors = []; this._tracers = new Map(); - var mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config)); + const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config)); this.resource = (_a = mergedConfig.resource) !== null && _a !== void 0 ? _a : Resource.empty(); this.resource = Resource.default().merge(this.resource); this._config = Object.assign({}, mergedConfig, { resource: this.resource, }); - var defaultExporter = this._buildExporterFromEnv(); + const defaultExporter = this._buildExporterFromEnv(); if (defaultExporter !== undefined) { - var batchProcessor = new BatchSpanProcessor(defaultExporter); + const batchProcessor = new BatchSpanProcessor(defaultExporter); this.activeSpanProcessor = batchProcessor; } else { this.activeSpanProcessor = new NoopSpanProcessor(); } } - BasicTracerProvider.prototype.getTracer = function (name, version, options) { - var key = name + "@" + (version || '') + ":" + ((options === null || options === void 0 ? void 0 : options.schemaUrl) || ''); + getTracer(name, version, options) { + const key = `${name}@${version || ''}:${(options === null || options === void 0 ? void 0 : options.schemaUrl) || ''}`; if (!this._tracers.has(key)) { - this._tracers.set(key, new Tracer({ name: name, version: version, schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl }, this._config, this)); + this._tracers.set(key, new Tracer({ name, version, schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl }, this._config, this)); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this._tracers.get(key); - }; + } /** * Adds a new {@link SpanProcessor} to this tracer. * @param spanProcessor the new SpanProcessor to be added. */ - BasicTracerProvider.prototype.addSpanProcessor = function (spanProcessor) { + addSpanProcessor(spanProcessor) { if (this._registeredSpanProcessors.length === 0) { // since we might have enabled by default a batchProcessor, we disable it // before adding the new one this.activeSpanProcessor .shutdown() - .catch(function (err) { - return index.src.diag.error('Error while trying to shutdown current span processor', err); - }); + .catch(err => traceApi.diag.error('Error while trying to shutdown current span processor', err)); } this._registeredSpanProcessors.push(spanProcessor); this.activeSpanProcessor = new MultiSpanProcessor(this._registeredSpanProcessors); - }; - BasicTracerProvider.prototype.getActiveSpanProcessor = function () { + } + getActiveSpanProcessor() { return this.activeSpanProcessor; - }; + } /** * Register this TracerProvider for use with the OpenTelemetry API. * Undefined values may be replaced with defaults, and @@ -8386,48 +3103,47 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * * @param config Configuration object for SDK registration */ - BasicTracerProvider.prototype.register = function (config) { - if (config === void 0) { config = {}; } - index.src.trace.setGlobalTracerProvider(this); + register(config = {}) { + traceApi.trace.setGlobalTracerProvider(this); if (config.propagator === undefined) { config.propagator = this._buildPropagatorFromEnv(); } if (config.contextManager) { - index.src.context.setGlobalContextManager(config.contextManager); + traceApi.context.setGlobalContextManager(config.contextManager); } if (config.propagator) { - index.src.propagation.setGlobalPropagator(config.propagator); + traceApi.propagation.setGlobalPropagator(config.propagator); } - }; - BasicTracerProvider.prototype.forceFlush = function () { - var timeout = this._config.forceFlushTimeoutMillis; - var promises = this._registeredSpanProcessors.map(function (spanProcessor) { - return new Promise(function (resolve) { - var state; - var timeoutInterval = setTimeout(function () { - resolve(new Error("Span processor did not completed within timeout period of " + timeout + " ms")); + } + forceFlush() { + const timeout = this._config.forceFlushTimeoutMillis; + const promises = this._registeredSpanProcessors.map((spanProcessor) => { + return new Promise(resolve => { + let state; + const timeoutInterval = setTimeout(() => { + resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`)); state = exports.ForceFlushState.timeout; }, timeout); spanProcessor .forceFlush() - .then(function () { + .then(() => { clearTimeout(timeoutInterval); if (state !== exports.ForceFlushState.timeout) { state = exports.ForceFlushState.resolved; resolve(state); } }) - .catch(function (error) { + .catch(error => { clearTimeout(timeoutInterval); state = exports.ForceFlushState.error; resolve(error); }); }); }); - return new Promise(function (resolve, reject) { + return new Promise((resolve, reject) => { Promise.all(promises) - .then(function (results) { - var errors = results.filter(function (result) { return result !== exports.ForceFlushState.resolved; }); + .then(results => { + const errors = results.filter(result => result !== exports.ForceFlushState.resolved); if (errors.length > 0) { reject(errors); } @@ -8435,12 +3151,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function resolve(); } }) - .catch(function (error) { return reject([error]); }); + .catch(error => reject([error])); }); - }; - BasicTracerProvider.prototype.shutdown = function () { + } + shutdown() { return this.activeSpanProcessor.shutdown(); - }; + } /** * TS cannot yet infer the type of this.constructor: * https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146 @@ -8448,26 +3164,25 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * The type of the registered component maps should be the same across all * classes in the inheritance tree. */ - BasicTracerProvider.prototype._getPropagator = function (name) { + _getPropagator(name) { var _a; return (_a = this.constructor._registeredPropagators.get(name)) === null || _a === void 0 ? void 0 : _a(); - }; - BasicTracerProvider.prototype._getSpanExporter = function (name) { + } + _getSpanExporter(name) { var _a; return (_a = this.constructor._registeredExporters.get(name)) === null || _a === void 0 ? void 0 : _a(); - }; - BasicTracerProvider.prototype._buildPropagatorFromEnv = function () { - var _this = this; + } + _buildPropagatorFromEnv() { // per spec, propagators from env must be deduplicated - var uniquePropagatorNames = Array.from(new Set(getEnv().OTEL_PROPAGATORS)); - var propagators = uniquePropagatorNames.map(function (name) { - var propagator = _this._getPropagator(name); + const uniquePropagatorNames = Array.from(new Set(getEnv().OTEL_PROPAGATORS)); + const propagators = uniquePropagatorNames.map(name => { + const propagator = this._getPropagator(name); if (!propagator) { - index.src.diag.warn("Propagator \"" + name + "\" requested through environment variable is unavailable."); + traceApi.diag.warn(`Propagator "${name}" requested through environment variable is unavailable.`); } return propagator; }); - var validPropagators = propagators.reduce(function (list, item) { + const validPropagators = propagators.reduce((list, item) => { if (item) { list.push(item); } @@ -8484,24 +3199,23 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function propagators: validPropagators, }); } - }; - BasicTracerProvider.prototype._buildExporterFromEnv = function () { - var exporterName = getEnv().OTEL_TRACES_EXPORTER; + } + _buildExporterFromEnv() { + const exporterName = getEnv().OTEL_TRACES_EXPORTER; if (exporterName === 'none' || exporterName === '') return; - var exporter = this._getSpanExporter(exporterName); + const exporter = this._getSpanExporter(exporterName); if (!exporter) { - index.src.diag.error("Exporter \"" + exporterName + "\" requested through environment variable is unavailable."); + traceApi.diag.error(`Exporter "${exporterName}" requested through environment variable is unavailable.`); } return exporter; - }; - BasicTracerProvider._registeredPropagators = new Map([ - ['tracecontext', function () { return new W3CTraceContextPropagator(); }], - ['baggage', function () { return new W3CBaggagePropagator(); }], - ]); - BasicTracerProvider._registeredExporters = new Map(); - return BasicTracerProvider; - }()); + } + } + BasicTracerProvider._registeredPropagators = new Map([ + ['tracecontext', () => new W3CTraceContextPropagator()], + ['baggage', () => new W3CBaggagePropagator()], + ]); + BasicTracerProvider._registeredExporters = new Map(); /* * Copyright The OpenTelemetry Authors @@ -8518,17 +3232,6 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __values = (this && this.__values) || function(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."); - }; /** * This is implementation of {@link SpanExporter} that prints spans to the * console. This class can be used for diagnostic purposes. @@ -8536,35 +3239,33 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time. */ /* eslint-disable no-console */ - var ConsoleSpanExporter = /** @class */ (function () { - function ConsoleSpanExporter() { - } + class ConsoleSpanExporter { /** * Export spans. * @param spans * @param resultCallback */ - ConsoleSpanExporter.prototype.export = function (spans, resultCallback) { + export(spans, resultCallback) { return this._sendSpans(spans, resultCallback); - }; + } /** * Shutdown the exporter. */ - ConsoleSpanExporter.prototype.shutdown = function () { + shutdown() { this._sendSpans([]); return this.forceFlush(); - }; + } /** * Exports any pending spans in exporter */ - ConsoleSpanExporter.prototype.forceFlush = function () { + forceFlush() { return Promise.resolve(); - }; + } /** * converts span info into more readable format * @param span */ - ConsoleSpanExporter.prototype._exportInfo = function (span) { + _exportInfo(span) { var _a; return { resource: { @@ -8584,33 +3285,21 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function events: span.events, links: span.links, }; - }; + } /** * Showing spans in console * @param spans * @param done */ - ConsoleSpanExporter.prototype._sendSpans = function (spans, done) { - var e_1, _a; - try { - for (var spans_1 = __values(spans), spans_1_1 = spans_1.next(); !spans_1_1.done; spans_1_1 = spans_1.next()) { - var span = spans_1_1.value; - console.dir(this._exportInfo(span), { depth: 3 }); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (spans_1_1 && !spans_1_1.done && (_a = spans_1.return)) _a.call(spans_1); - } - finally { if (e_1) throw e_1.error; } + _sendSpans(spans, done) { + for (const span of spans) { + console.dir(this._exportInfo(span), { depth: 3 }); } if (done) { return done({ code: ExportResultCode.SUCCESS }); } - }; - return ConsoleSpanExporter; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -8627,38 +3316,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __read$1 = (this && this.__read) || function (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; - }; - var __spreadArray$1 = (this && this.__spreadArray) || function (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)); - }; /** * This class can be used for testing purposes. It stores the exported spans * in a list in memory that can be retrieved using the `getFinishedSpans()` * method. */ - var InMemorySpanExporter = /** @class */ (function () { - function InMemorySpanExporter() { + class InMemorySpanExporter { + constructor() { this._finishedSpans = []; /** * Indicates if the exporter has been "shutdown." @@ -8666,35 +3330,33 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function */ this._stopped = false; } - InMemorySpanExporter.prototype.export = function (spans, resultCallback) { - var _a; + export(spans, resultCallback) { if (this._stopped) return resultCallback({ code: ExportResultCode.FAILED, error: new Error('Exporter has been stopped'), }); - (_a = this._finishedSpans).push.apply(_a, __spreadArray$1([], __read$1(spans), false)); - setTimeout(function () { return resultCallback({ code: ExportResultCode.SUCCESS }); }, 0); - }; - InMemorySpanExporter.prototype.shutdown = function () { + this._finishedSpans.push(...spans); + setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0); + } + shutdown() { this._stopped = true; this._finishedSpans = []; return this.forceFlush(); - }; + } /** * Exports any pending spans in the exporter */ - InMemorySpanExporter.prototype.forceFlush = function () { + forceFlush() { return Promise.resolve(); - }; - InMemorySpanExporter.prototype.reset = function () { + } + reset() { this._finishedSpans = []; - }; - InMemorySpanExporter.prototype.getFinishedSpans = function () { + } + getFinishedSpans() { return this._finishedSpans; - }; - return InMemorySpanExporter; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -8711,42 +3373,6 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __awaiter = (this && this.__awaiter) || function (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()); - }); - }; - var __generator = (this && this.__generator) || function (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 }; - } - }; /** * An implementation of the {@link SpanProcessor} that converts the {@link Span} * to {@link ReadableSpan} and passes it to the configured exporter. @@ -8755,80 +3381,63 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead. */ - var SimpleSpanProcessor = /** @class */ (function () { - function SimpleSpanProcessor(_exporter) { + class SimpleSpanProcessor { + constructor(_exporter) { this._exporter = _exporter; this._shutdownOnce = new BindOnceFuture(this._shutdown, this); this._unresolvedExports = new Set(); } - SimpleSpanProcessor.prototype.forceFlush = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - // await unresolved resources before resolving - return [4 /*yield*/, Promise.all(Array.from(this._unresolvedExports))]; - case 1: - // await unresolved resources before resolving - _a.sent(); - if (!this._exporter.forceFlush) return [3 /*break*/, 3]; - return [4 /*yield*/, this._exporter.forceFlush()]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - SimpleSpanProcessor.prototype.onStart = function (_span, _parentContext) { }; - SimpleSpanProcessor.prototype.onEnd = function (span) { - var _this = this; + async forceFlush() { + // await unresolved resources before resolving + await Promise.all(Array.from(this._unresolvedExports)); + if (this._exporter.forceFlush) { + await this._exporter.forceFlush(); + } + } + onStart(_span, _parentContext) { } + onEnd(span) { var _a, _b; if (this._shutdownOnce.isCalled) { return; } - if ((span.spanContext().traceFlags & index.src.TraceFlags.SAMPLED) === 0) { + if ((span.spanContext().traceFlags & traceApi.TraceFlags.SAMPLED) === 0) { return; } - var doExport = function () { - return internal - ._export(_this._exporter, [span]) - .then(function (result) { - var _a; - if (result.code !== ExportResultCode.SUCCESS) { - globalErrorHandler((_a = result.error) !== null && _a !== void 0 ? _a : new Error("SimpleSpanProcessor: span export failed (status " + result + ")")); - } - }) - .catch(function (error) { - globalErrorHandler(error); - }); - }; + const doExport = () => internal + ._export(this._exporter, [span]) + .then((result) => { + var _a; + if (result.code !== ExportResultCode.SUCCESS) { + globalErrorHandler((_a = result.error) !== null && _a !== void 0 ? _a : new Error(`SimpleSpanProcessor: span export failed (status ${result})`)); + } + }) + .catch(error => { + globalErrorHandler(error); + }); // Avoid scheduling a promise to make the behavior more predictable and easier to test if (span.resource.asyncAttributesPending) { - var exportPromise_1 = (_b = (_a = span.resource).waitForAsyncAttributes) === null || _b === void 0 ? void 0 : _b.call(_a).then(function () { - if (exportPromise_1 != null) { - _this._unresolvedExports.delete(exportPromise_1); + const exportPromise = (_b = (_a = span.resource).waitForAsyncAttributes) === null || _b === void 0 ? void 0 : _b.call(_a).then(() => { + if (exportPromise != null) { + this._unresolvedExports.delete(exportPromise); } return doExport(); - }, function (err) { return globalErrorHandler(err); }); + }, err => globalErrorHandler(err)); // store the unresolved exports - if (exportPromise_1 != null) { - this._unresolvedExports.add(exportPromise_1); + if (exportPromise != null) { + this._unresolvedExports.add(exportPromise); } } else { void doExport(); } - }; - SimpleSpanProcessor.prototype.shutdown = function () { + } + shutdown() { return this._shutdownOnce.call(); - }; - SimpleSpanProcessor.prototype._shutdown = function () { + } + _shutdown() { return this._exporter.shutdown(); - }; - return SimpleSpanProcessor; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -8845,37 +3454,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __read = (this && this.__read) || function (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; - }; - var __spreadArray = (this && this.__spreadArray) || function (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)); - }; /** * Stack Context Manager for managing the state in web * it doesn't fully support the async calls though */ - var StackContextManager = /** @class */ (function () { - function StackContextManager() { + class StackContextManager { + constructor() { /** * whether the context manager is enabled or not */ @@ -8883,7 +3467,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function /** * Keeps the reference to current context */ - this._currentContext = index.src.ROOT_CONTEXT; + this._currentContext = traceApi.ROOT_CONTEXT; } /** * @@ -8891,16 +3475,10 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param target Function to be executed within the context */ // eslint-disable-next-line @typescript-eslint/ban-types - StackContextManager.prototype._bindFunction = function (context, target) { - if (context === void 0) { context = index.src.ROOT_CONTEXT; } - var manager = this; - var contextWrapper = function () { - var _this = this; - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return manager.with(context, function () { return target.apply(_this, args); }); + _bindFunction(context = traceApi.ROOT_CONTEXT, target) { + const manager = this; + const contextWrapper = function (...args) { + return manager.with(context, () => target.apply(this, args)); }; Object.defineProperty(contextWrapper, 'length', { enumerable: false, @@ -8909,20 +3487,20 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function value: target.length, }); return contextWrapper; - }; + } /** * Returns the active context */ - StackContextManager.prototype.active = function () { + active() { return this._currentContext; - }; + } /** * Binds a the certain context or the active one to the target function and then returns the target * @param context A context (span) to be bind to target * @param target a function or event emitter. When target or one of its callbacks is called, * the provided context will be used as the active context for the duration of the call. */ - StackContextManager.prototype.bind = function (context, target) { + bind(context, target) { // if no specific context to propagate is given, we use the current one if (context === undefined) { context = this.active(); @@ -8931,26 +3509,26 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return this._bindFunction(context, target); } return target; - }; + } /** * Disable the context manager (clears the current context) */ - StackContextManager.prototype.disable = function () { - this._currentContext = index.src.ROOT_CONTEXT; + disable() { + this._currentContext = traceApi.ROOT_CONTEXT; this._enabled = false; return this; - }; + } /** * Enables the context manager and creates a default(root) context */ - StackContextManager.prototype.enable = function () { + enable() { if (this._enabled) { return this; } this._enabled = true; - this._currentContext = index.src.ROOT_CONTEXT; + this._currentContext = traceApi.ROOT_CONTEXT; return this; - }; + } /** * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window. * The context will be set as active @@ -8959,22 +3537,17 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ - StackContextManager.prototype.with = function (context, fn, thisArg) { - var args = []; - for (var _i = 3; _i < arguments.length; _i++) { - args[_i - 3] = arguments[_i]; - } - var previousContext = this._currentContext; - this._currentContext = context || index.src.ROOT_CONTEXT; + with(context, fn, thisArg, ...args) { + const previousContext = this._currentContext; + this._currentContext = context || traceApi.ROOT_CONTEXT; try { - return fn.call.apply(fn, __spreadArray([thisArg], __read(args), false)); + return fn.call(thisArg, ...args); } finally { this._currentContext = previousContext; } - }; - return StackContextManager; - }()); + } + } /* * Copyright The OpenTelemetry Authors @@ -8991,33 +3564,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * See the License for the specific language governing permissions and * limitations under the License. */ - var __extends = (this && this.__extends) || (function () { - 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); - }; - return function (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 __()); - }; - })(); /** * This class represents a web tracer with {@link StackContextManager} */ - var WebTracerProvider = /** @class */ (function (_super) { - __extends(WebTracerProvider, _super); + class WebTracerProvider extends BasicTracerProvider { /** * Constructs a new Tracer instance. * @param config Web Tracer config */ - function WebTracerProvider(config) { - if (config === void 0) { config = {}; } - var _this = _super.call(this, config) || this; + constructor(config = {}) { + super(config); if (config.contextManager) { throw ('contextManager should be defined in register method not in' + ' constructor'); @@ -9025,7 +3581,6 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function if (config.propagator) { throw 'propagator should be defined in register method not in constructor'; } - return _this; } /** * Register this TracerProvider for use with the OpenTelemetry API. @@ -9034,18 +3589,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function * * @param config Configuration object for SDK registration */ - WebTracerProvider.prototype.register = function (config) { - if (config === void 0) { config = {}; } + register(config = {}) { if (config.contextManager === undefined) { config.contextManager = new StackContextManager(); } if (config.contextManager) { config.contextManager.enable(); } - _super.prototype.register.call(this, config); - }; - return WebTracerProvider; - }(BasicTracerProvider)); + super.register(config); + } + } /* * Copyright The OpenTelemetry Authors @@ -9088,7 +3641,7 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function PerformanceTimingNames["UNLOAD_EVENT_START"] = "unloadEventStart"; })(exports.PerformanceTimingNames || (exports.PerformanceTimingNames = {})); - var urlNormalizingAnchor; + let urlNormalizingAnchor; function getUrlNormalizingAnchor() { if (!urlNormalizingAnchor) { urlNormalizingAnchor = document.createElement("a"); @@ -9099,12 +3652,12 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return (key in obj); } function addSpanNetworkEvent(span, performanceName, entries, refPerfName) { - var perfTime = undefined; - var refTime = undefined; + let perfTime = undefined; + let refTime = undefined; if (hasKey(entries, performanceName) && typeof entries[performanceName] === "number") { perfTime = entries[performanceName]; } - var refName = refPerfName || exports.PerformanceTimingNames.FETCH_START; + const refName = refPerfName || exports.PerformanceTimingNames.FETCH_START; if (hasKey(entries, refName) && typeof entries[refName] === "number") { refTime = entries[refName]; } @@ -9126,19 +3679,19 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function addSpanNetworkEvent(span, exports.PerformanceTimingNames.REQUEST_START, resource); addSpanNetworkEvent(span, exports.PerformanceTimingNames.RESPONSE_START, resource); addSpanNetworkEvent(span, exports.PerformanceTimingNames.RESPONSE_END, resource); - var encodedLength = resource[exports.PerformanceTimingNames.ENCODED_BODY_SIZE]; + const encodedLength = resource[exports.PerformanceTimingNames.ENCODED_BODY_SIZE]; if (encodedLength !== undefined) { - span.setAttribute(src.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, encodedLength); + span.setAttribute(SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, encodedLength); } - var decodedLength = resource[exports.PerformanceTimingNames.DECODED_BODY_SIZE]; + const decodedLength = resource[exports.PerformanceTimingNames.DECODED_BODY_SIZE]; if (decodedLength !== undefined && encodedLength !== decodedLength) { - span.setAttribute(src.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, decodedLength); + span.setAttribute(SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, decodedLength); } } function sortResources(filteredResources) { - return filteredResources.slice().sort(function (a, b) { - var valueA = a[exports.PerformanceTimingNames.FETCH_START]; - var valueB = b[exports.PerformanceTimingNames.FETCH_START]; + return filteredResources.slice().sort((a, b) => { + const valueA = a[exports.PerformanceTimingNames.FETCH_START]; + const valueB = b[exports.PerformanceTimingNames.FETCH_START]; if (valueA > valueB) { return 1; } else if (valueA < valueB) { @@ -9150,13 +3703,10 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function function getOrigin() { return typeof location !== "undefined" ? location.origin : undefined; } - function getResource(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType) { - if (ignoredResources === void 0) { - ignoredResources = new WeakSet(); - } - var parsedSpanUrl = parseUrl(spanUrl); + function getResource(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources = new WeakSet(), initiatorType) { + const parsedSpanUrl = parseUrl(spanUrl); spanUrl = parsedSpanUrl.toString(); - var filteredResources = filterResourcesForSpan(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType); + const filteredResources = filterResourcesForSpan(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType); if (filteredResources.length === 0) { return { mainRequest: undefined @@ -9167,19 +3717,19 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function mainRequest: filteredResources[0] }; } - var sorted = sortResources(filteredResources); + const sorted = sortResources(filteredResources); if (parsedSpanUrl.origin !== getOrigin() && sorted.length > 1) { - var corsPreFlightRequest = sorted[0]; - var mainRequest = findMainRequest(sorted, corsPreFlightRequest[exports.PerformanceTimingNames.RESPONSE_END], endTimeHR); - var responseEnd = corsPreFlightRequest[exports.PerformanceTimingNames.RESPONSE_END]; - var fetchStart = mainRequest[exports.PerformanceTimingNames.FETCH_START]; + let corsPreFlightRequest = sorted[0]; + let mainRequest = findMainRequest(sorted, corsPreFlightRequest[exports.PerformanceTimingNames.RESPONSE_END], endTimeHR); + const responseEnd = corsPreFlightRequest[exports.PerformanceTimingNames.RESPONSE_END]; + const fetchStart = mainRequest[exports.PerformanceTimingNames.FETCH_START]; if (fetchStart < responseEnd) { mainRequest = corsPreFlightRequest; corsPreFlightRequest = undefined; } return { - corsPreFlightRequest: corsPreFlightRequest, - mainRequest: mainRequest + corsPreFlightRequest, + mainRequest }; } else { return { @@ -9188,16 +3738,16 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function } } function findMainRequest(resources, corsPreFlightRequestEndTime, spanEndTimeHR) { - var spanEndTime = hrTimeToNanoseconds(spanEndTimeHR); - var minTime = hrTimeToNanoseconds(timeInputToHrTime(corsPreFlightRequestEndTime)); - var mainRequest = resources[1]; - var bestGap; - var length = resources.length; - for (var i = 1; i < length; i++) { - var resource = resources[i]; - var resourceStartTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.FETCH_START])); - var resourceEndTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.RESPONSE_END])); - var currentGap = spanEndTime - resourceEndTime; + const spanEndTime = hrTimeToNanoseconds(spanEndTimeHR); + const minTime = hrTimeToNanoseconds(timeInputToHrTime(corsPreFlightRequestEndTime)); + let mainRequest = resources[1]; + let bestGap; + const length = resources.length; + for (let i = 1; i < length; i++) { + const resource = resources[i]; + const resourceStartTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.FETCH_START])); + const resourceEndTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.RESPONSE_END])); + const currentGap = spanEndTime - resourceEndTime; if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) { bestGap = currentGap; mainRequest = resource; @@ -9206,15 +3756,15 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return mainRequest; } function filterResourcesForSpan(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType) { - var startTime = hrTimeToNanoseconds(startTimeHR); - var endTime = hrTimeToNanoseconds(endTimeHR); - var filteredResources = resources.filter(function (resource) { - var resourceStartTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.FETCH_START])); - var resourceEndTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.RESPONSE_END])); + const startTime = hrTimeToNanoseconds(startTimeHR); + const endTime = hrTimeToNanoseconds(endTimeHR); + let filteredResources = resources.filter(resource => { + const resourceStartTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.FETCH_START])); + const resourceEndTime = hrTimeToNanoseconds(timeInputToHrTime(resource[exports.PerformanceTimingNames.RESPONSE_END])); return resource.initiatorType.toLowerCase() === (initiatorType || "xmlhttprequest") && resource.name === spanUrl && resourceStartTime >= startTime && resourceEndTime <= endTime; }); if (filteredResources.length > 0) { - filteredResources = filteredResources.filter(function (resource) { + filteredResources = filteredResources.filter(resource => { return !ignoredResources.has(resource); }); } @@ -9224,23 +3774,23 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function if (typeof URL === "function") { return new URL(url, typeof document !== "undefined" ? document.baseURI : typeof location !== "undefined" ? location.href : undefined); } - var element = getUrlNormalizingAnchor(); + const element = getUrlNormalizingAnchor(); element.href = url; return element; } function normalizeUrl(url) { - var urlLike = parseUrl(url); + const urlLike = parseUrl(url); return urlLike.href; } function getElementXPath(target, optimised) { if (target.nodeType === Node.DOCUMENT_NODE) { return "/"; } - var targetValue = getNodeValue(target, optimised); + const targetValue = getNodeValue(target, optimised); if (optimised && targetValue.indexOf("@id") > 0) { return targetValue; } - var xpath = ""; + let xpath = ""; if (target.parentNode) { xpath += getElementXPath(target.parentNode, false); } @@ -9251,13 +3801,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function if (!target.parentNode) { return 0; } - var allowedTypes = [target.nodeType]; + const allowedTypes = [target.nodeType]; if (target.nodeType === Node.CDATA_SECTION_NODE) { allowedTypes.push(Node.TEXT_NODE); } - var elements = Array.from(target.parentNode.childNodes); - elements = elements.filter(function (element) { - var localName = element.localName; + let elements = Array.from(target.parentNode.childNodes); + elements = elements.filter(element => { + const localName = element.localName; return allowedTypes.indexOf(element.nodeType) >= 0 && localName === target.localName; }); if (elements.length >= 1) { @@ -9266,13 +3816,13 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return 0; } function getNodeValue(target, optimised) { - var nodeType = target.nodeType; - var index = getNodeIndex(target); - var nodeValue = ""; + const nodeType = target.nodeType; + const index = getNodeIndex(target); + let nodeValue = ""; if (nodeType === Node.ELEMENT_NODE) { - var id = target.getAttribute("id"); + const id = target.getAttribute("id"); if (optimised && id) { - return "//*[@id=\"" + id + "\"]"; + return `//*[@id="${id}"]`; } nodeValue = target.localName; } else if (nodeType === Node.TEXT_NODE || nodeType === Node.CDATA_SECTION_NODE) { @@ -9283,22 +3833,20 @@ sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function return ""; } if (nodeValue && index > 1) { - return "/" + nodeValue + "[" + index + "]"; + return `/${nodeValue}[${index}]`; } - return "/" + nodeValue; + return `/${nodeValue}`; } function shouldPropagateTraceHeaders(spanUrl, propagateTraceHeaderCorsUrls) { - var propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || []; + let propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || []; if (typeof propagateTraceHeaderUrls === "string" || propagateTraceHeaderUrls instanceof RegExp) { propagateTraceHeaderUrls = [propagateTraceHeaderUrls]; } - var parsedSpanUrl = parseUrl(spanUrl); + const parsedSpanUrl = parseUrl(spanUrl); if (parsedSpanUrl.origin === getOrigin()) { return true; } else { - return propagateTraceHeaderUrls.some(function (propagateTraceHeaderUrl) { - return urlMatches(spanUrl, propagateTraceHeaderUrl); - }); + return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl => urlMatches(spanUrl, propagateTraceHeaderUrl)); } } diff --git a/packages/ui5-tooling-modules/test/__snap__/09909941/index3.js b/packages/ui5-tooling-modules/test/__snap__/09909941/index3.js deleted file mode 100644 index fbbe0dcc..00000000 --- a/packages/ui5-tooling-modules/test/__snap__/09909941/index3.js +++ /dev/null @@ -1,2415 +0,0 @@ -sap.ui.define(['exports'], (function (exports) { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - var src = {}; - - var utils$1 = {}; - - var diag$1 = {}; - - var ComponentLogger = {}; - - var globalUtils = {}; - - var browser = {}; - - var globalThis$1 = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(globalThis$1, "__esModule", { value: true }); - globalThis$1._globalThis = void 0; - // Updates to this file should also be replicated to @opentelemetry/core too. - /** - * - globalThis (New standard) - * - self (Will return the current window instance for supported browsers) - * - window (fallback for older browser implementations) - * - global (NodeJS implementation) - * - (When all else fails) - */ - /** only globals that common to node and browsers are allowed */ - // eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef - globalThis$1._globalThis = typeof globalThis === 'object' - ? globalThis - : typeof self === 'object' - ? self - : typeof window === 'object' - ? window - : typeof commonjsGlobal === 'object' - ? commonjsGlobal - : {}; - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(globalThis$1, exports); - - } (browser)); - - var version = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(version, "__esModule", { value: true }); - version.VERSION = void 0; - // this is autogenerated file, see scripts/version-update.js - version.VERSION = '1.9.0'; - - var semver = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(semver, "__esModule", { value: true }); - semver.isCompatible = semver._makeCompatibilityCheck = void 0; - const version_1$1 = version; - const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; - /** - * Create a function to test an API version to see if it is compatible with the provided ownVersion. - * - * The returned function has the following semantics: - * - Exact match is always compatible - * - Major versions must match exactly - * - 1.x package cannot use global 2.x package - * - 2.x package cannot use global 1.x package - * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API - * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects - * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 - * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor - * - Patch and build tag differences are not considered at this time - * - * @param ownVersion version which should be checked against - */ - function _makeCompatibilityCheck(ownVersion) { - const acceptedVersions = new Set([ownVersion]); - const rejectedVersions = new Set(); - const myVersionMatch = ownVersion.match(re); - if (!myVersionMatch) { - // we cannot guarantee compatibility so we always return noop - return () => false; - } - const ownVersionParsed = { - major: +myVersionMatch[1], - minor: +myVersionMatch[2], - patch: +myVersionMatch[3], - prerelease: myVersionMatch[4], - }; - // if ownVersion has a prerelease tag, versions must match exactly - if (ownVersionParsed.prerelease != null) { - return function isExactmatch(globalVersion) { - return globalVersion === ownVersion; - }; - } - function _reject(v) { - rejectedVersions.add(v); - return false; - } - function _accept(v) { - acceptedVersions.add(v); - return true; - } - return function isCompatible(globalVersion) { - if (acceptedVersions.has(globalVersion)) { - return true; - } - if (rejectedVersions.has(globalVersion)) { - return false; - } - const globalVersionMatch = globalVersion.match(re); - if (!globalVersionMatch) { - // cannot parse other version - // we cannot guarantee compatibility so we always noop - return _reject(globalVersion); - } - const globalVersionParsed = { - major: +globalVersionMatch[1], - minor: +globalVersionMatch[2], - patch: +globalVersionMatch[3], - prerelease: globalVersionMatch[4], - }; - // if globalVersion has a prerelease tag, versions must match exactly - if (globalVersionParsed.prerelease != null) { - return _reject(globalVersion); - } - // major versions must match - if (ownVersionParsed.major !== globalVersionParsed.major) { - return _reject(globalVersion); - } - if (ownVersionParsed.major === 0) { - if (ownVersionParsed.minor === globalVersionParsed.minor && - ownVersionParsed.patch <= globalVersionParsed.patch) { - return _accept(globalVersion); - } - return _reject(globalVersion); - } - if (ownVersionParsed.minor <= globalVersionParsed.minor) { - return _accept(globalVersion); - } - return _reject(globalVersion); - }; - } - semver._makeCompatibilityCheck = _makeCompatibilityCheck; - /** - * Test an API version to see if it is compatible with this API. - * - * - Exact match is always compatible - * - Major versions must match exactly - * - 1.x package cannot use global 2.x package - * - 2.x package cannot use global 1.x package - * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API - * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects - * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 - * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor - * - Patch and build tag differences are not considered at this time - * - * @param version version of the API requesting an instance of the global API - */ - semver.isCompatible = _makeCompatibilityCheck(version_1$1.VERSION); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(globalUtils, "__esModule", { value: true }); - globalUtils.unregisterGlobal = globalUtils.getGlobal = globalUtils.registerGlobal = void 0; - const platform_1 = browser; - const version_1 = version; - const semver_1 = semver; - const major = version_1.VERSION.split('.')[0]; - const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); - const _global = platform_1._globalThis; - function registerGlobal(type, instance, diag, allowOverride = false) { - var _a; - const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { - version: version_1.VERSION, - }); - if (!allowOverride && api[type]) { - // already registered an API of this type - const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); - diag.error(err.stack || err.message); - return false; - } - if (api.version !== version_1.VERSION) { - // All registered APIs must be of the same version exactly - const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); - diag.error(err.stack || err.message); - return false; - } - api[type] = instance; - diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); - return true; - } - globalUtils.registerGlobal = registerGlobal; - function getGlobal(type) { - var _a, _b; - const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { - return; - } - return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; - } - globalUtils.getGlobal = getGlobal; - function unregisterGlobal(type, diag) { - diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); - const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; - if (api) { - delete api[type]; - } - } - globalUtils.unregisterGlobal = unregisterGlobal; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(ComponentLogger, "__esModule", { value: true }); - ComponentLogger.DiagComponentLogger = void 0; - const global_utils_1$5 = globalUtils; - /** - * Component Logger which is meant to be used as part of any component which - * will add automatically additional namespace in front of the log message. - * It will then forward all message to global diag logger - * @example - * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); - * cLogger.debug('test'); - * // @opentelemetry/instrumentation-http test - */ - class DiagComponentLogger { - constructor(props) { - this._namespace = props.namespace || 'DiagComponentLogger'; - } - debug(...args) { - return logProxy('debug', this._namespace, args); - } - error(...args) { - return logProxy('error', this._namespace, args); - } - info(...args) { - return logProxy('info', this._namespace, args); - } - warn(...args) { - return logProxy('warn', this._namespace, args); - } - verbose(...args) { - return logProxy('verbose', this._namespace, args); - } - } - ComponentLogger.DiagComponentLogger = DiagComponentLogger; - function logProxy(funcName, namespace, args) { - const logger = (0, global_utils_1$5.getGlobal)('diag'); - // shortcut if logger not set - if (!logger) { - return; - } - args.unshift(namespace); - return logger[funcName](...args); - } - - var logLevelLogger = {}; - - var types = {}; - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiagLogLevel = void 0; - (function (DiagLogLevel) { - /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ - DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; - /** Identifies an error scenario */ - DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; - /** Identifies a warning scenario */ - DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; - /** General informational log message */ - DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; - /** General debug log message */ - DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; - /** - * Detailed trace level logging should only be used for development, should only be set - * in a development environment. - */ - DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; - /** Used to set the logging level to include all logging */ - DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; - })(exports.DiagLogLevel || (exports.DiagLogLevel = {})); - - } (types)); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(logLevelLogger, "__esModule", { value: true }); - logLevelLogger.createLogLevelDiagLogger = void 0; - const types_1$1 = types; - function createLogLevelDiagLogger(maxLevel, logger) { - if (maxLevel < types_1$1.DiagLogLevel.NONE) { - maxLevel = types_1$1.DiagLogLevel.NONE; - } - else if (maxLevel > types_1$1.DiagLogLevel.ALL) { - maxLevel = types_1$1.DiagLogLevel.ALL; - } - // In case the logger is null or undefined - logger = logger || {}; - function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; - if (typeof theFunc === 'function' && maxLevel >= theLevel) { - return theFunc.bind(logger); - } - return function () { }; - } - return { - error: _filterFunc('error', types_1$1.DiagLogLevel.ERROR), - warn: _filterFunc('warn', types_1$1.DiagLogLevel.WARN), - info: _filterFunc('info', types_1$1.DiagLogLevel.INFO), - debug: _filterFunc('debug', types_1$1.DiagLogLevel.DEBUG), - verbose: _filterFunc('verbose', types_1$1.DiagLogLevel.VERBOSE), - }; - } - logLevelLogger.createLogLevelDiagLogger = createLogLevelDiagLogger; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(diag$1, "__esModule", { value: true }); - diag$1.DiagAPI = void 0; - const ComponentLogger_1 = ComponentLogger; - const logLevelLogger_1 = logLevelLogger; - const types_1 = types; - const global_utils_1$4 = globalUtils; - const API_NAME$4 = 'diag'; - /** - * Singleton object which represents the entry point to the OpenTelemetry internal - * diagnostic API - */ - class DiagAPI { - /** - * Private internal constructor - * @private - */ - constructor() { - function _logProxy(funcName) { - return function (...args) { - const logger = (0, global_utils_1$4.getGlobal)('diag'); - // shortcut if logger not set - if (!logger) - return; - return logger[funcName](...args); - }; - } - // Using self local variable for minification purposes as 'this' cannot be minified - const self = this; - // DiagAPI specific functions - const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { - var _a, _b, _c; - if (logger === self) { - // There isn't much we can do here. - // Logging to the console might break the user application. - // Try to log to self. If a logger was previously registered it will receive the log. - const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); - self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); - return false; - } - if (typeof optionsOrLogLevel === 'number') { - optionsOrLogLevel = { - logLevel: optionsOrLogLevel, - }; - } - const oldLogger = (0, global_utils_1$4.getGlobal)('diag'); - const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); - // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { - const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; - oldLogger.warn(`Current logger will be overwritten from ${stack}`); - newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); - } - return (0, global_utils_1$4.registerGlobal)('diag', newLogger, self, true); - }; - self.setLogger = setLogger; - self.disable = () => { - (0, global_utils_1$4.unregisterGlobal)(API_NAME$4, self); - }; - self.createComponentLogger = (options) => { - return new ComponentLogger_1.DiagComponentLogger(options); - }; - self.verbose = _logProxy('verbose'); - self.debug = _logProxy('debug'); - self.info = _logProxy('info'); - self.warn = _logProxy('warn'); - self.error = _logProxy('error'); - } - /** Get the singleton instance of the DiagAPI API */ - static instance() { - if (!this._instance) { - this._instance = new DiagAPI(); - } - return this._instance; - } - } - diag$1.DiagAPI = DiagAPI; - - var baggageImpl = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(baggageImpl, "__esModule", { value: true }); - baggageImpl.BaggageImpl = void 0; - class BaggageImpl { - constructor(entries) { - this._entries = entries ? new Map(entries) : new Map(); - } - getEntry(key) { - const entry = this._entries.get(key); - if (!entry) { - return undefined; - } - return Object.assign({}, entry); - } - getAllEntries() { - return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); - } - setEntry(key, entry) { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.set(key, entry); - return newBaggage; - } - removeEntry(key) { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.delete(key); - return newBaggage; - } - removeEntries(...keys) { - const newBaggage = new BaggageImpl(this._entries); - for (const key of keys) { - newBaggage._entries.delete(key); - } - return newBaggage; - } - clear() { - return new BaggageImpl(); - } - } - baggageImpl.BaggageImpl = BaggageImpl; - - var symbol = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(symbol, "__esModule", { value: true }); - symbol.baggageEntryMetadataSymbol = void 0; - /** - * Symbol used to make BaggageEntryMetadata an opaque type - */ - symbol.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(utils$1, "__esModule", { value: true }); - utils$1.baggageEntryMetadataFromString = utils$1.createBaggage = void 0; - const diag_1$5 = diag$1; - const baggage_impl_1 = baggageImpl; - const symbol_1 = symbol; - const diag = diag_1$5.DiagAPI.instance(); - /** - * Create a new Baggage with optional entries - * - * @param entries An array of baggage entries the new baggage should contain - */ - function createBaggage(entries = {}) { - return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); - } - utils$1.createBaggage = createBaggage; - /** - * Create a serializable BaggageEntryMetadata object from a string. - * - * @param str string metadata. Format is currently not defined by the spec and has no special meaning. - * - */ - function baggageEntryMetadataFromString(str) { - if (typeof str !== 'string') { - diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); - str = ''; - } - return { - __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString() { - return str; - }, - }; - } - utils$1.baggageEntryMetadataFromString = baggageEntryMetadataFromString; - - var context$1 = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(context$1, "__esModule", { value: true }); - context$1.ROOT_CONTEXT = context$1.createContextKey = void 0; - /** Get a key to uniquely identify a context value */ - function createContextKey(description) { - // The specification states that for the same input, multiple calls should - // return different keys. Due to the nature of the JS dependency management - // system, this creates problems where multiple versions of some package - // could hold different keys for the same property. - // - // Therefore, we use Symbol.for which returns the same key for the same input. - return Symbol.for(description); - } - context$1.createContextKey = createContextKey; - class BaseContext { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - constructor(parentContext) { - // for minification - const self = this; - self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = (key) => self._currentContext.get(key); - self.setValue = (key, value) => { - const context = new BaseContext(self._currentContext); - context._currentContext.set(key, value); - return context; - }; - self.deleteValue = (key) => { - const context = new BaseContext(self._currentContext); - context._currentContext.delete(key); - return context; - }; - } - } - /** The root context is used as the default parent context when there is no active context */ - context$1.ROOT_CONTEXT = new BaseContext(); - - var consoleLogger = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(consoleLogger, "__esModule", { value: true }); - consoleLogger.DiagConsoleLogger = void 0; - const consoleMap = [ - { n: 'error', c: 'error' }, - { n: 'warn', c: 'warn' }, - { n: 'info', c: 'info' }, - { n: 'debug', c: 'debug' }, - { n: 'verbose', c: 'trace' }, - ]; - /** - * A simple Immutable Console based diagnostic logger which will output any messages to the Console. - * If you want to limit the amount of logging to a specific level or lower use the - * {@link createLogLevelDiagLogger} - */ - class DiagConsoleLogger { - constructor() { - function _consoleFunc(funcName) { - return function (...args) { - if (console) { - // Some environments only expose the console when the F12 developer console is open - // eslint-disable-next-line no-console - let theFunc = console[funcName]; - if (typeof theFunc !== 'function') { - // Not all environments support all functions - // eslint-disable-next-line no-console - theFunc = console.log; - } - // One last final check - if (typeof theFunc === 'function') { - return theFunc.apply(console, args); - } - } - }; - } - for (let i = 0; i < consoleMap.length; i++) { - this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); - } - } - } - consoleLogger.DiagConsoleLogger = DiagConsoleLogger; - - var NoopMeter = {}; - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; - /** - * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses - * constant NoopMetrics for all of its methods. - */ - class NoopMeter { - constructor() { } - /** - * @see {@link Meter.createGauge} - */ - createGauge(_name, _options) { - return exports.NOOP_GAUGE_METRIC; - } - /** - * @see {@link Meter.createHistogram} - */ - createHistogram(_name, _options) { - return exports.NOOP_HISTOGRAM_METRIC; - } - /** - * @see {@link Meter.createCounter} - */ - createCounter(_name, _options) { - return exports.NOOP_COUNTER_METRIC; - } - /** - * @see {@link Meter.createUpDownCounter} - */ - createUpDownCounter(_name, _options) { - return exports.NOOP_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableGauge} - */ - createObservableGauge(_name, _options) { - return exports.NOOP_OBSERVABLE_GAUGE_METRIC; - } - /** - * @see {@link Meter.createObservableCounter} - */ - createObservableCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableUpDownCounter} - */ - createObservableUpDownCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.addBatchObservableCallback} - */ - addBatchObservableCallback(_callback, _observables) { } - /** - * @see {@link Meter.removeBatchObservableCallback} - */ - removeBatchObservableCallback(_callback) { } - } - exports.NoopMeter = NoopMeter; - class NoopMetric { - } - exports.NoopMetric = NoopMetric; - class NoopCounterMetric extends NoopMetric { - add(_value, _attributes) { } - } - exports.NoopCounterMetric = NoopCounterMetric; - class NoopUpDownCounterMetric extends NoopMetric { - add(_value, _attributes) { } - } - exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; - class NoopGaugeMetric extends NoopMetric { - record(_value, _attributes) { } - } - exports.NoopGaugeMetric = NoopGaugeMetric; - class NoopHistogramMetric extends NoopMetric { - record(_value, _attributes) { } - } - exports.NoopHistogramMetric = NoopHistogramMetric; - class NoopObservableMetric { - addCallback(_callback) { } - removeCallback(_callback) { } - } - exports.NoopObservableMetric = NoopObservableMetric; - class NoopObservableCounterMetric extends NoopObservableMetric { - } - exports.NoopObservableCounterMetric = NoopObservableCounterMetric; - class NoopObservableGaugeMetric extends NoopObservableMetric { - } - exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; - class NoopObservableUpDownCounterMetric extends NoopObservableMetric { - } - exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; - exports.NOOP_METER = new NoopMeter(); - // Synchronous instruments - exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); - exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric(); - exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); - exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); - // Asynchronous instruments - exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); - exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); - exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); - /** - * Create a no-op Meter - */ - function createNoopMeter() { - return exports.NOOP_METER; - } - exports.createNoopMeter = createNoopMeter; - - } (NoopMeter)); - - var Metric = {}; - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueType = void 0; - (function (ValueType) { - ValueType[ValueType["INT"] = 0] = "INT"; - ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; - })(exports.ValueType || (exports.ValueType = {})); - - } (Metric)); - - var TextMapPropagator = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(TextMapPropagator, "__esModule", { value: true }); - TextMapPropagator.defaultTextMapSetter = TextMapPropagator.defaultTextMapGetter = void 0; - TextMapPropagator.defaultTextMapGetter = { - get(carrier, key) { - if (carrier == null) { - return undefined; - } - return carrier[key]; - }, - keys(carrier) { - if (carrier == null) { - return []; - } - return Object.keys(carrier); - }, - }; - TextMapPropagator.defaultTextMapSetter = { - set(carrier, key, value) { - if (carrier == null) { - return; - } - carrier[key] = value; - }, - }; - - var ProxyTracer$1 = {}; - - var NoopTracer$1 = {}; - - var context = {}; - - var NoopContextManager$1 = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(NoopContextManager$1, "__esModule", { value: true }); - NoopContextManager$1.NoopContextManager = void 0; - const context_1$4 = context$1; - class NoopContextManager { - active() { - return context_1$4.ROOT_CONTEXT; - } - with(_context, fn, thisArg, ...args) { - return fn.call(thisArg, ...args); - } - bind(_context, target) { - return target; - } - enable() { - return this; - } - disable() { - return this; - } - } - NoopContextManager$1.NoopContextManager = NoopContextManager; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(context, "__esModule", { value: true }); - context.ContextAPI = void 0; - const NoopContextManager_1 = NoopContextManager$1; - const global_utils_1$3 = globalUtils; - const diag_1$4 = diag$1; - const API_NAME$3 = 'context'; - const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); - /** - * Singleton object which represents the entry point to the OpenTelemetry Context API - */ - class ContextAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Context API */ - static getInstance() { - if (!this._instance) { - this._instance = new ContextAPI(); - } - return this._instance; - } - /** - * Set the current context manager. - * - * @returns true if the context manager was successfully registered, else false - */ - setGlobalContextManager(contextManager) { - return (0, global_utils_1$3.registerGlobal)(API_NAME$3, contextManager, diag_1$4.DiagAPI.instance()); - } - /** - * Get the currently active context - */ - active() { - return this._getContextManager().active(); - } - /** - * Execute a function with an active context - * - * @param context context to be active during function execution - * @param fn function to execute in a context - * @param thisArg optional receiver to be used for calling fn - * @param args optional arguments forwarded to fn - */ - with(context, fn, thisArg, ...args) { - return this._getContextManager().with(context, fn, thisArg, ...args); - } - /** - * Bind a context to a target function or event emitter - * - * @param context context to bind to the event emitter or function. Defaults to the currently active context - * @param target function or event emitter to bind - */ - bind(context, target) { - return this._getContextManager().bind(context, target); - } - _getContextManager() { - return (0, global_utils_1$3.getGlobal)(API_NAME$3) || NOOP_CONTEXT_MANAGER; - } - /** Disable and remove the global context manager */ - disable() { - this._getContextManager().disable(); - (0, global_utils_1$3.unregisterGlobal)(API_NAME$3, diag_1$4.DiagAPI.instance()); - } - } - context.ContextAPI = ContextAPI; - - var contextUtils = {}; - - var NonRecordingSpan$1 = {}; - - var invalidSpanConstants = {}; - - var trace_flags = {}; - - (function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.TraceFlags = void 0; - (function (TraceFlags) { - /** Represents no flag set. */ - TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; - /** Bit to represent whether trace is sampled in trace flags. */ - TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; - })(exports.TraceFlags || (exports.TraceFlags = {})); - - } (trace_flags)); - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; - const trace_flags_1 = trace_flags; - exports.INVALID_SPANID = '0000000000000000'; - exports.INVALID_TRACEID = '00000000000000000000000000000000'; - exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, - }; - - } (invalidSpanConstants)); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(NonRecordingSpan$1, "__esModule", { value: true }); - NonRecordingSpan$1.NonRecordingSpan = void 0; - const invalid_span_constants_1$1 = invalidSpanConstants; - /** - * The NonRecordingSpan is the default {@link Span} that is used when no Span - * implementation is available. All operations are no-op including context - * propagation. - */ - class NonRecordingSpan { - constructor(_spanContext = invalid_span_constants_1$1.INVALID_SPAN_CONTEXT) { - this._spanContext = _spanContext; - } - // Returns a SpanContext. - spanContext() { - return this._spanContext; - } - // By default does nothing - setAttribute(_key, _value) { - return this; - } - // By default does nothing - setAttributes(_attributes) { - return this; - } - // By default does nothing - addEvent(_name, _attributes) { - return this; - } - addLink(_link) { - return this; - } - addLinks(_links) { - return this; - } - // By default does nothing - setStatus(_status) { - return this; - } - // By default does nothing - updateName(_name) { - return this; - } - // By default does nothing - end(_endTime) { } - // isRecording always returns false for NonRecordingSpan. - isRecording() { - return false; - } - // By default does nothing - recordException(_exception, _time) { } - } - NonRecordingSpan$1.NonRecordingSpan = NonRecordingSpan; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(contextUtils, "__esModule", { value: true }); - contextUtils.getSpanContext = contextUtils.setSpanContext = contextUtils.deleteSpan = contextUtils.setSpan = contextUtils.getActiveSpan = contextUtils.getSpan = void 0; - const context_1$3 = context$1; - const NonRecordingSpan_1$2 = NonRecordingSpan$1; - const context_2$1 = context; - /** - * span key - */ - const SPAN_KEY = (0, context_1$3.createContextKey)('OpenTelemetry Context Key SPAN'); - /** - * Return the span if one exists - * - * @param context context to get span from - */ - function getSpan(context) { - return context.getValue(SPAN_KEY) || undefined; - } - contextUtils.getSpan = getSpan; - /** - * Gets the span from the current context, if one exists. - */ - function getActiveSpan() { - return getSpan(context_2$1.ContextAPI.getInstance().active()); - } - contextUtils.getActiveSpan = getActiveSpan; - /** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ - function setSpan(context, span) { - return context.setValue(SPAN_KEY, span); - } - contextUtils.setSpan = setSpan; - /** - * Remove current span stored in the context - * - * @param context context to delete span from - */ - function deleteSpan(context) { - return context.deleteValue(SPAN_KEY); - } - contextUtils.deleteSpan = deleteSpan; - /** - * Wrap span context in a NoopSpan and set as span in a new - * context - * - * @param context context to set active span on - * @param spanContext span context to be wrapped - */ - function setSpanContext(context, spanContext) { - return setSpan(context, new NonRecordingSpan_1$2.NonRecordingSpan(spanContext)); - } - contextUtils.setSpanContext = setSpanContext; - /** - * Get the span context of the span if it exists. - * - * @param context context to get values from - */ - function getSpanContext(context) { - var _a; - return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); - } - contextUtils.getSpanContext = getSpanContext; - - var spancontextUtils = {}; - - Object.defineProperty(spancontextUtils, "__esModule", { value: true }); - spancontextUtils.wrapSpanContext = spancontextUtils.isSpanContextValid = spancontextUtils.isValidSpanId = spancontextUtils.isValidTraceId = void 0; - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - const invalid_span_constants_1 = invalidSpanConstants; - const NonRecordingSpan_1$1 = NonRecordingSpan$1; - const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; - const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; - function isValidTraceId(traceId) { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; - } - spancontextUtils.isValidTraceId = isValidTraceId; - function isValidSpanId(spanId) { - return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; - } - spancontextUtils.isValidSpanId = isValidSpanId; - /** - * Returns true if this {@link SpanContext} is valid. - * @return true if this {@link SpanContext} is valid. - */ - function isSpanContextValid(spanContext) { - return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); - } - spancontextUtils.isSpanContextValid = isSpanContextValid; - /** - * Wrap the given {@link SpanContext} in a new non-recording {@link Span} - * - * @param spanContext span context to be wrapped - * @returns a new non-recording {@link Span} with the provided context - */ - function wrapSpanContext(spanContext) { - return new NonRecordingSpan_1$1.NonRecordingSpan(spanContext); - } - spancontextUtils.wrapSpanContext = wrapSpanContext; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(NoopTracer$1, "__esModule", { value: true }); - NoopTracer$1.NoopTracer = void 0; - const context_1$2 = context; - const context_utils_1$1 = contextUtils; - const NonRecordingSpan_1 = NonRecordingSpan$1; - const spancontext_utils_1$1 = spancontextUtils; - const contextApi$1 = context_1$2.ContextAPI.getInstance(); - /** - * No-op implementations of {@link Tracer}. - */ - class NoopTracer { - // startSpan starts a noop span. - startSpan(name, options, context = contextApi$1.active()) { - const root = Boolean(options === null || options === void 0 ? void 0 : options.root); - if (root) { - return new NonRecordingSpan_1.NonRecordingSpan(); - } - const parentFromContext = context && (0, context_utils_1$1.getSpanContext)(context); - if (isSpanContext(parentFromContext) && - (0, spancontext_utils_1$1.isSpanContextValid)(parentFromContext)) { - return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); - } - else { - return new NonRecordingSpan_1.NonRecordingSpan(); - } - } - startActiveSpan(name, arg2, arg3, arg4) { - let opts; - let ctx; - let fn; - if (arguments.length < 2) { - return; - } - else if (arguments.length === 2) { - fn = arg2; - } - else if (arguments.length === 3) { - opts = arg2; - fn = arg3; - } - else { - opts = arg2; - ctx = arg3; - fn = arg4; - } - const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi$1.active(); - const span = this.startSpan(name, opts, parentContext); - const contextWithSpanSet = (0, context_utils_1$1.setSpan)(parentContext, span); - return contextApi$1.with(contextWithSpanSet, fn, undefined, span); - } - } - NoopTracer$1.NoopTracer = NoopTracer; - function isSpanContext(spanContext) { - return (typeof spanContext === 'object' && - typeof spanContext['spanId'] === 'string' && - typeof spanContext['traceId'] === 'string' && - typeof spanContext['traceFlags'] === 'number'); - } - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(ProxyTracer$1, "__esModule", { value: true }); - ProxyTracer$1.ProxyTracer = void 0; - const NoopTracer_1$1 = NoopTracer$1; - const NOOP_TRACER = new NoopTracer_1$1.NoopTracer(); - /** - * Proxy tracer provided by the proxy tracer provider - */ - class ProxyTracer { - constructor(_provider, name, version, options) { - this._provider = _provider; - this.name = name; - this.version = version; - this.options = options; - } - startSpan(name, options, context) { - return this._getTracer().startSpan(name, options, context); - } - startActiveSpan(_name, _options, _context, _fn) { - const tracer = this._getTracer(); - return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - } - /** - * Try to get a tracer from the proxy tracer provider. - * If the proxy tracer provider has no delegate, return a noop tracer. - */ - _getTracer() { - if (this._delegate) { - return this._delegate; - } - const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); - if (!tracer) { - return NOOP_TRACER; - } - this._delegate = tracer; - return this._delegate; - } - } - ProxyTracer$1.ProxyTracer = ProxyTracer; - - var ProxyTracerProvider$1 = {}; - - var NoopTracerProvider$1 = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(NoopTracerProvider$1, "__esModule", { value: true }); - NoopTracerProvider$1.NoopTracerProvider = void 0; - const NoopTracer_1 = NoopTracer$1; - /** - * An implementation of the {@link TracerProvider} which returns an impotent - * Tracer for all calls to `getTracer`. - * - * All operations are no-op. - */ - class NoopTracerProvider { - getTracer(_name, _version, _options) { - return new NoopTracer_1.NoopTracer(); - } - } - NoopTracerProvider$1.NoopTracerProvider = NoopTracerProvider; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(ProxyTracerProvider$1, "__esModule", { value: true }); - ProxyTracerProvider$1.ProxyTracerProvider = void 0; - const ProxyTracer_1 = ProxyTracer$1; - const NoopTracerProvider_1 = NoopTracerProvider$1; - const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); - /** - * Tracer provider which provides {@link ProxyTracer}s. - * - * Before a delegate is set, tracers provided are NoOp. - * When a delegate is set, traces are provided from the delegate. - * When a delegate is set after tracers have already been provided, - * all tracers already provided will use the provided delegate implementation. - */ - class ProxyTracerProvider { - /** - * Get a {@link ProxyTracer} - */ - getTracer(name, version, options) { - var _a; - return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); - } - getDelegate() { - var _a; - return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - } - /** - * Set the delegate tracer provider - */ - setDelegate(delegate) { - this._delegate = delegate; - } - getDelegateTracer(name, version, options) { - var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); - } - } - ProxyTracerProvider$1.ProxyTracerProvider = ProxyTracerProvider; - - var SamplingResult = {}; - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SamplingDecision = void 0; - (function (SamplingDecision) { - /** - * `Span.isRecording() === false`, span will not be recorded and all events - * and attributes will be dropped. - */ - SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; - /** - * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} - * MUST NOT be set. - */ - SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; - /** - * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} - * MUST be set. - */ - SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; - })(exports.SamplingDecision || (exports.SamplingDecision = {})); - - } (SamplingResult)); - - var span_kind = {}; - - (function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SpanKind = void 0; - (function (SpanKind) { - /** Default value. Indicates that the span is used internally. */ - SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; - /** - * Indicates that the span covers server-side handling of an RPC or other - * remote request. - */ - SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; - /** - * Indicates that the span covers the client-side wrapper around an RPC or - * other remote request. - */ - SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; - /** - * Indicates that the span describes producer sending a message to a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; - /** - * Indicates that the span describes consumer receiving a message from a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; - })(exports.SpanKind || (exports.SpanKind = {})); - - } (span_kind)); - - var status = {}; - - (function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SpanStatusCode = void 0; - (function (SpanStatusCode) { - /** - * The default status. - */ - SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; - /** - * The operation has been validated by an Application developer or - * Operator to have completed successfully. - */ - SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; - /** - * The operation contains an error. - */ - SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; - })(exports.SpanStatusCode || (exports.SpanStatusCode = {})); - - } (status)); - - var utils = {}; - - var tracestateImpl = {}; - - var tracestateValidators = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(tracestateValidators, "__esModule", { value: true }); - tracestateValidators.validateValue = tracestateValidators.validateKey = void 0; - const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; - const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; - const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; - const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); - const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; - const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; - /** - * Key is opaque string up to 256 characters printable. It MUST begin with a - * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, - * underscores _, dashes -, asterisks *, and forward slashes /. - * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the - * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. - * see https://www.w3.org/TR/trace-context/#key - */ - function validateKey(key) { - return VALID_KEY_REGEX.test(key); - } - tracestateValidators.validateKey = validateKey; - /** - * Value is opaque string up to 256 characters printable ASCII RFC0020 - * characters (i.e., the range 0x20 to 0x7E) except comma , and =. - */ - function validateValue(value) { - return (VALID_VALUE_BASE_REGEX.test(value) && - !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); - } - tracestateValidators.validateValue = validateValue; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(tracestateImpl, "__esModule", { value: true }); - tracestateImpl.TraceStateImpl = void 0; - const tracestate_validators_1 = tracestateValidators; - const MAX_TRACE_STATE_ITEMS = 32; - const MAX_TRACE_STATE_LEN = 512; - const LIST_MEMBERS_SEPARATOR = ','; - const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; - /** - * TraceState must be a class and not a simple object type because of the spec - * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). - * - * Here is the list of allowed mutations: - * - New key-value pair should be added into the beginning of the list - * - The value of any key can be updated. Modified keys MUST be moved to the - * beginning of the list. - */ - class TraceStateImpl { - constructor(rawTraceState) { - this._internalState = new Map(); - if (rawTraceState) - this._parse(rawTraceState); - } - set(key, value) { - // TODO: Benchmark the different approaches(map vs list) and - // use the faster one. - const traceState = this._clone(); - if (traceState._internalState.has(key)) { - traceState._internalState.delete(key); - } - traceState._internalState.set(key, value); - return traceState; - } - unset(key) { - const traceState = this._clone(); - traceState._internalState.delete(key); - return traceState; - } - get(key) { - return this._internalState.get(key); - } - serialize() { - return this._keys() - .reduce((agg, key) => { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); - return agg; - }, []) - .join(LIST_MEMBERS_SEPARATOR); - } - _parse(rawTraceState) { - if (rawTraceState.length > MAX_TRACE_STATE_LEN) - return; - this._internalState = rawTraceState - .split(LIST_MEMBERS_SEPARATOR) - .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce((agg, part) => { - const listMember = part.trim(); // Optional Whitespace (OWS) handling - const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); - if (i !== -1) { - const key = listMember.slice(0, i); - const value = listMember.slice(i + 1, part.length); - if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { - agg.set(key, value); - } - } - return agg; - }, new Map()); - // Because of the reverse() requirement, trunc must be done after map is created - if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { - this._internalState = new Map(Array.from(this._internalState.entries()) - .reverse() // Use reverse same as original tracestate parse chain - .slice(0, MAX_TRACE_STATE_ITEMS)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const traceState = new TraceStateImpl(); - traceState._internalState = new Map(this._internalState); - return traceState; - } - } - tracestateImpl.TraceStateImpl = TraceStateImpl; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(utils, "__esModule", { value: true }); - utils.createTraceState = void 0; - const tracestate_impl_1 = tracestateImpl; - function createTraceState(rawTraceState) { - return new tracestate_impl_1.TraceStateImpl(rawTraceState); - } - utils.createTraceState = createTraceState; - - var contextApi = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(contextApi, "__esModule", { value: true }); - contextApi.context = void 0; - // Split module-level variable definition into separate files to allow - // tree-shaking on each api instance. - const context_1$1 = context; - /** Entrypoint for context API */ - contextApi.context = context_1$1.ContextAPI.getInstance(); - - var diagApi = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(diagApi, "__esModule", { value: true }); - diagApi.diag = void 0; - // Split module-level variable definition into separate files to allow - // tree-shaking on each api instance. - const diag_1$3 = diag$1; - /** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ - diagApi.diag = diag_1$3.DiagAPI.instance(); - - var metricsApi = {}; - - var metrics = {}; - - var NoopMeterProvider$1 = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(NoopMeterProvider$1, "__esModule", { value: true }); - NoopMeterProvider$1.NOOP_METER_PROVIDER = NoopMeterProvider$1.NoopMeterProvider = void 0; - const NoopMeter_1 = NoopMeter; - /** - * An implementation of the {@link MeterProvider} which returns an impotent Meter - * for all calls to `getMeter` - */ - class NoopMeterProvider { - getMeter(_name, _version, _options) { - return NoopMeter_1.NOOP_METER; - } - } - NoopMeterProvider$1.NoopMeterProvider = NoopMeterProvider; - NoopMeterProvider$1.NOOP_METER_PROVIDER = new NoopMeterProvider(); - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(metrics, "__esModule", { value: true }); - metrics.MetricsAPI = void 0; - const NoopMeterProvider_1 = NoopMeterProvider$1; - const global_utils_1$2 = globalUtils; - const diag_1$2 = diag$1; - const API_NAME$2 = 'metrics'; - /** - * Singleton object which represents the entry point to the OpenTelemetry Metrics API - */ - class MetricsAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Metrics API */ - static getInstance() { - if (!this._instance) { - this._instance = new MetricsAPI(); - } - return this._instance; - } - /** - * Set the current global meter provider. - * Returns true if the meter provider was successfully registered, else false. - */ - setGlobalMeterProvider(provider) { - return (0, global_utils_1$2.registerGlobal)(API_NAME$2, provider, diag_1$2.DiagAPI.instance()); - } - /** - * Returns the global meter provider. - */ - getMeterProvider() { - return (0, global_utils_1$2.getGlobal)(API_NAME$2) || NoopMeterProvider_1.NOOP_METER_PROVIDER; - } - /** - * Returns a meter from the global meter provider. - */ - getMeter(name, version, options) { - return this.getMeterProvider().getMeter(name, version, options); - } - /** Remove the global meter provider */ - disable() { - (0, global_utils_1$2.unregisterGlobal)(API_NAME$2, diag_1$2.DiagAPI.instance()); - } - } - metrics.MetricsAPI = MetricsAPI; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(metricsApi, "__esModule", { value: true }); - metricsApi.metrics = void 0; - // Split module-level variable definition into separate files to allow - // tree-shaking on each api instance. - const metrics_1 = metrics; - /** Entrypoint for metrics API */ - metricsApi.metrics = metrics_1.MetricsAPI.getInstance(); - - var propagationApi = {}; - - var propagation = {}; - - var NoopTextMapPropagator$1 = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(NoopTextMapPropagator$1, "__esModule", { value: true }); - NoopTextMapPropagator$1.NoopTextMapPropagator = void 0; - /** - * No-op implementations of {@link TextMapPropagator}. - */ - class NoopTextMapPropagator { - /** Noop inject function does nothing */ - inject(_context, _carrier) { } - /** Noop extract function does nothing and returns the input context */ - extract(context, _carrier) { - return context; - } - fields() { - return []; - } - } - NoopTextMapPropagator$1.NoopTextMapPropagator = NoopTextMapPropagator; - - var contextHelpers = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(contextHelpers, "__esModule", { value: true }); - contextHelpers.deleteBaggage = contextHelpers.setBaggage = contextHelpers.getActiveBaggage = contextHelpers.getBaggage = void 0; - const context_1 = context; - const context_2 = context$1; - /** - * Baggage key - */ - const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); - /** - * Retrieve the current baggage from the given context - * - * @param {Context} Context that manage all context values - * @returns {Baggage} Extracted baggage from the context - */ - function getBaggage(context) { - return context.getValue(BAGGAGE_KEY) || undefined; - } - contextHelpers.getBaggage = getBaggage; - /** - * Retrieve the current baggage from the active/current context - * - * @returns {Baggage} Extracted baggage from the context - */ - function getActiveBaggage() { - return getBaggage(context_1.ContextAPI.getInstance().active()); - } - contextHelpers.getActiveBaggage = getActiveBaggage; - /** - * Store a baggage in the given context - * - * @param {Context} Context that manage all context values - * @param {Baggage} baggage that will be set in the actual context - */ - function setBaggage(context, baggage) { - return context.setValue(BAGGAGE_KEY, baggage); - } - contextHelpers.setBaggage = setBaggage; - /** - * Delete the baggage stored in the given context - * - * @param {Context} Context that manage all context values - */ - function deleteBaggage(context) { - return context.deleteValue(BAGGAGE_KEY); - } - contextHelpers.deleteBaggage = deleteBaggage; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(propagation, "__esModule", { value: true }); - propagation.PropagationAPI = void 0; - const global_utils_1$1 = globalUtils; - const NoopTextMapPropagator_1 = NoopTextMapPropagator$1; - const TextMapPropagator_1 = TextMapPropagator; - const context_helpers_1 = contextHelpers; - const utils_1 = utils$1; - const diag_1$1 = diag$1; - const API_NAME$1 = 'propagation'; - const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); - /** - * Singleton object which represents the entry point to the OpenTelemetry Propagation API - */ - class PropagationAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { - this.createBaggage = utils_1.createBaggage; - this.getBaggage = context_helpers_1.getBaggage; - this.getActiveBaggage = context_helpers_1.getActiveBaggage; - this.setBaggage = context_helpers_1.setBaggage; - this.deleteBaggage = context_helpers_1.deleteBaggage; - } - /** Get the singleton instance of the Propagator API */ - static getInstance() { - if (!this._instance) { - this._instance = new PropagationAPI(); - } - return this._instance; - } - /** - * Set the current propagator. - * - * @returns true if the propagator was successfully registered, else false - */ - setGlobalPropagator(propagator) { - return (0, global_utils_1$1.registerGlobal)(API_NAME$1, propagator, diag_1$1.DiagAPI.instance()); - } - /** - * Inject context into a carrier to be propagated inter-process - * - * @param context Context carrying tracing data to inject - * @param carrier carrier to inject context into - * @param setter Function used to set values on the carrier - */ - inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { - return this._getGlobalPropagator().inject(context, carrier, setter); - } - /** - * Extract context from a carrier - * - * @param context Context which the newly created context will inherit from - * @param carrier Carrier to extract context from - * @param getter Function used to extract keys from a carrier - */ - extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { - return this._getGlobalPropagator().extract(context, carrier, getter); - } - /** - * Return a list of all fields which may be used by the propagator. - */ - fields() { - return this._getGlobalPropagator().fields(); - } - /** Remove the global propagator */ - disable() { - (0, global_utils_1$1.unregisterGlobal)(API_NAME$1, diag_1$1.DiagAPI.instance()); - } - _getGlobalPropagator() { - return (0, global_utils_1$1.getGlobal)(API_NAME$1) || NOOP_TEXT_MAP_PROPAGATOR; - } - } - propagation.PropagationAPI = PropagationAPI; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(propagationApi, "__esModule", { value: true }); - propagationApi.propagation = void 0; - // Split module-level variable definition into separate files to allow - // tree-shaking on each api instance. - const propagation_1 = propagation; - /** Entrypoint for propagation API */ - propagationApi.propagation = propagation_1.PropagationAPI.getInstance(); - - var traceApi = {}; - - var trace = {}; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(trace, "__esModule", { value: true }); - trace.TraceAPI = void 0; - const global_utils_1 = globalUtils; - const ProxyTracerProvider_1 = ProxyTracerProvider$1; - const spancontext_utils_1 = spancontextUtils; - const context_utils_1 = contextUtils; - const diag_1 = diag$1; - const API_NAME = 'trace'; - /** - * Singleton object which represents the entry point to the OpenTelemetry Tracing API - */ - class TraceAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { - this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; - this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; - this.deleteSpan = context_utils_1.deleteSpan; - this.getSpan = context_utils_1.getSpan; - this.getActiveSpan = context_utils_1.getActiveSpan; - this.getSpanContext = context_utils_1.getSpanContext; - this.setSpan = context_utils_1.setSpan; - this.setSpanContext = context_utils_1.setSpanContext; - } - /** Get the singleton instance of the Trace API */ - static getInstance() { - if (!this._instance) { - this._instance = new TraceAPI(); - } - return this._instance; - } - /** - * Set the current global tracer. - * - * @returns true if the tracer provider was successfully registered, else false - */ - setGlobalTracerProvider(provider) { - const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); - if (success) { - this._proxyTracerProvider.setDelegate(provider); - } - return success; - } - /** - * Returns the global tracer provider. - */ - getTracerProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; - } - /** - * Returns a tracer from the global tracer provider. - */ - getTracer(name, version) { - return this.getTracerProvider().getTracer(name, version); - } - /** Remove the global tracer provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - } - } - trace.TraceAPI = TraceAPI; - - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(traceApi, "__esModule", { value: true }); - traceApi.trace = void 0; - // Split module-level variable definition into separate files to allow - // tree-shaking on each api instance. - const trace_1 = trace; - /** Entrypoint for trace API */ - traceApi.trace = trace_1.TraceAPI.getInstance(); - - (function (exports) { - /* - * Copyright The OpenTelemetry Authors - * - * 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 - * - * https://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. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; - var utils_1 = utils$1; - Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }); - // Context APIs - var context_1 = context$1; - Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function () { return context_1.createContextKey; } }); - Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } }); - // Diag APIs - var consoleLogger_1 = consoleLogger; - Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } }); - var types_1 = types; - Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function () { return types_1.DiagLogLevel; } }); - // Metrics APIs - var NoopMeter_1 = NoopMeter; - Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } }); - var Metric_1 = Metric; - Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return Metric_1.ValueType; } }); - // Propagation APIs - var TextMapPropagator_1 = TextMapPropagator; - Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } }); - Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } }); - var ProxyTracer_1 = ProxyTracer$1; - Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } }); - var ProxyTracerProvider_1 = ProxyTracerProvider$1; - Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } }); - var SamplingResult_1 = SamplingResult; - Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } }); - var span_kind_1 = span_kind; - Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return span_kind_1.SpanKind; } }); - var status_1 = status; - Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return status_1.SpanStatusCode; } }); - var trace_flags_1 = trace_flags; - Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function () { return trace_flags_1.TraceFlags; } }); - var utils_2 = utils; - Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function () { return utils_2.createTraceState; } }); - var spancontext_utils_1 = spancontextUtils; - Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }); - Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }); - Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } }); - var invalid_span_constants_1 = invalidSpanConstants; - Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }); - Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }); - Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }); - // Split module-level variable definition into separate files to allow - // tree-shaking on each api instance. - const context_api_1 = contextApi; - Object.defineProperty(exports, "context", { enumerable: true, get: function () { return context_api_1.context; } }); - const diag_api_1 = diagApi; - Object.defineProperty(exports, "diag", { enumerable: true, get: function () { return diag_api_1.diag; } }); - const metrics_api_1 = metricsApi; - Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return metrics_api_1.metrics; } }); - const propagation_api_1 = propagationApi; - Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return propagation_api_1.propagation; } }); - const trace_api_1 = traceApi; - Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return trace_api_1.trace; } }); - // Default export. - exports.default = { - context: context_api_1.context, - diag: diag_api_1.diag, - metrics: metrics_api_1.metrics, - propagation: propagation_api_1.propagation, - trace: trace_api_1.trace, - }; - - } (src)); - - exports.commonjsGlobal = commonjsGlobal; - exports.src = src; - -})); diff --git a/packages/ui5-tooling-modules/test/__snap__/09909941/trace-api.js b/packages/ui5-tooling-modules/test/__snap__/09909941/trace-api.js new file mode 100644 index 00000000..d5d93ce5 --- /dev/null +++ b/packages/ui5-tooling-modules/test/__snap__/09909941/trace-api.js @@ -0,0 +1,1850 @@ +sap.ui.define(['exports'], (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Updates to this file should also be replicated to @opentelemetry/core too. + /** + * - globalThis (New standard) + * - self (Will return the current window instance for supported browsers) + * - window (fallback for older browser implementations) + * - global (NodeJS implementation) + * - (When all else fails) + */ + /** only globals that common to node and browsers are allowed */ + // eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef + const _globalThis = typeof globalThis === 'object' + ? globalThis + : typeof self === 'object' + ? self + : typeof window === 'object' + ? window + : typeof global$1 === 'object' + ? global$1 + : {}; + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // this is autogenerated file, see scripts/version-update.js + const VERSION = '1.9.0'; + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + /** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ + function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + // we cannot guarantee compatibility so we always return noop + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], + }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + // cannot parse other version + // we cannot guarantee compatibility so we always noop + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], + }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + // major versions must match + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && + ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; + } + /** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ + const isCompatible = _makeCompatibilityCheck(VERSION); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const major = VERSION.split('.')[0]; + const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); + const _global = _globalThis; + function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: VERSION, + }); + if (!allowOverride && api[type]) { + // already registered an API of this type + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== VERSION) { + // All registered APIs must be of the same version exactly + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`); + return true; + } + function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !isCompatible(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; + } + function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ + class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + debug(...args) { + return logProxy('debug', this._namespace, args); + } + error(...args) { + return logProxy('error', this._namespace, args); + } + info(...args) { + return logProxy('info', this._namespace, args); + } + warn(...args) { + return logProxy('warn', this._namespace, args); + } + verbose(...args) { + return logProxy('verbose', this._namespace, args); + } + } + function logProxy(funcName, namespace, args) { + const logger = getGlobal('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName](...args); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ + exports.DiagLogLevel = void 0; + (function (DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; + })(exports.DiagLogLevel || (exports.DiagLogLevel = {})); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < exports.DiagLogLevel.NONE) { + maxLevel = exports.DiagLogLevel.NONE; + } + else if (maxLevel > exports.DiagLogLevel.ALL) { + maxLevel = exports.DiagLogLevel.ALL; + } + // In case the logger is null or undefined + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === 'function' && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function () { }; + } + return { + error: _filterFunc('error', exports.DiagLogLevel.ERROR), + warn: _filterFunc('warn', exports.DiagLogLevel.WARN), + info: _filterFunc('info', exports.DiagLogLevel.INFO), + debug: _filterFunc('debug', exports.DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', exports.DiagLogLevel.VERBOSE), + }; + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const API_NAME$4 = 'diag'; + /** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ + class DiagAPI { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function (...args) { + const logger = getGlobal('diag'); + // shortcut if logger not set + if (!logger) + return; + return logger[funcName](...args); + }; + } + // Using self local variable for minification purposes as 'this' cannot be minified + const self = this; + // DiagAPI specific functions + const setLogger = (logger, optionsOrLogLevel = { logLevel: exports.DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self) { + // There isn't much we can do here. + // Logging to the console might break the user application. + // Try to log to self. If a logger was previously registered it will receive the log. + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = getGlobal('diag'); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : exports.DiagLogLevel.INFO, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return registerGlobal('diag', newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + unregisterGlobal(API_NAME$4, self); + }; + self.createComponentLogger = (options) => { + return new DiagComponentLogger(options); + }; + self.verbose = _logProxy('verbose'); + self.debug = _logProxy('debug'); + self.info = _logProxy('info'); + self.warn = _logProxy('warn'); + self.error = _logProxy('error'); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl(); + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * Symbol used to make BaggageEntryMetadata an opaque type + */ + const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const diag$1 = DiagAPI.instance(); + /** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ + function createBaggage(entries = {}) { + return new BaggageImpl(new Map(Object.entries(entries))); + } + /** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ + function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag$1.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ''; + } + return { + __TYPE__: baggageEntryMetadataSymbol, + toString() { + return str; + }, + }; + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** Get a key to uniquely identify a context value */ + function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. + return Symbol.for(description); + } + class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + // for minification + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } + } + /** The root context is used as the default parent context when there is no active context */ + const ROOT_CONTEXT = new BaseContext(); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ + class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } + } + class NoopMetric { + } + class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } + } + class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } + } + class NoopGaugeMetric extends NoopMetric { + record(_value, _attributes) { } + } + class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } + } + class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } + } + class NoopObservableCounterMetric extends NoopObservableMetric { + } + class NoopObservableGaugeMetric extends NoopObservableMetric { + } + class NoopObservableUpDownCounterMetric extends NoopObservableMetric { + } + const NOOP_METER = new NoopMeter(); + // Synchronous instruments + const NOOP_COUNTER_METRIC = new NoopCounterMetric(); + const NOOP_GAUGE_METRIC = new NoopGaugeMetric(); + const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); + const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); + // Asynchronous instruments + const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); + const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); + const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); + /** + * Create a no-op Meter + */ + function createNoopMeter() { + return NOOP_METER; + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** The Type of value. It describes how the data is reported. */ + exports.ValueType = void 0; + (function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; + })(exports.ValueType || (exports.ValueType = {})); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return undefined; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + }, + }; + const defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + }, + }; + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + class NoopContextManager { + active() { + return ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const API_NAME$3 = 'context'; + const NOOP_CONTEXT_MANAGER = new NoopContextManager(); + /** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ + class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return registerGlobal(API_NAME$3, contextManager, DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context, target) { + return this._getContextManager().bind(context, target); + } + _getContextManager() { + return getGlobal(API_NAME$3) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + unregisterGlobal(API_NAME$3, DiagAPI.instance()); + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + exports.TraceFlags = void 0; + (function (TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; + })(exports.TraceFlags || (exports.TraceFlags = {})); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const INVALID_SPANID = '0000000000000000'; + const INVALID_TRACEID = '00000000000000000000000000000000'; + const INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: exports.TraceFlags.NONE, + }; + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ + class NonRecordingSpan { + constructor(_spanContext = INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * span key + */ + const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); + /** + * Return the span if one exists + * + * @param context context to get span from + */ + function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; + } + /** + * Gets the span from the current context, if one exists. + */ + function getActiveSpan() { + return getSpan(ContextAPI.getInstance().active()); + } + /** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ + function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); + } + /** + * Remove current span stored in the context + * + * @param context context to delete span from + */ + function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); + } + /** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ + function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan(spanContext)); + } + /** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ + function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; + const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; + function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; + } + function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; + } + /** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ + function isSpanContextValid(spanContext) { + return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); + } + /** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ + function wrapSpanContext(spanContext) { + return new NonRecordingSpan(spanContext); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const contextApi = ContextAPI.getInstance(); + /** + * No-op implementations of {@link Tracer}. + */ + class NoopTracer { + // startSpan starts a noop span. + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan(); + } + const parentFromContext = context && getSpanContext(context); + if (isSpanContext(parentFromContext) && + isSpanContextValid(parentFromContext)) { + return new NonRecordingSpan(parentFromContext); + } + else { + return new NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = setSpan(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } + } + function isSpanContext(spanContext) { + return (typeof spanContext === 'object' && + typeof spanContext['spanId'] === 'string' && + typeof spanContext['traceId'] === 'string' && + typeof spanContext['traceFlags'] === 'number'); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const NOOP_TRACER = new NoopTracer(); + /** + * Proxy tracer provided by the proxy tracer provider + */ + class ProxyTracer { + constructor(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ + class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer(); + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const NOOP_TRACER_PROVIDER = new NoopTracerProvider(); + /** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ + class ProxyTracerProvider { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version, options) { + var _a; + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options)); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ + exports.SamplingDecision = void 0; + (function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(exports.SamplingDecision || (exports.SamplingDecision = {})); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + exports.SpanKind = void 0; + (function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; + })(exports.SpanKind || (exports.SpanKind = {})); + + /** + * An enumeration of status codes. + */ + exports.SpanStatusCode = void 0; + (function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; + })(exports.SpanStatusCode || (exports.SpanStatusCode = {})); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Split module-level variable definition into separate files to allow + // tree-shaking on each api instance. + /** Entrypoint for context API */ + const context = ContextAPI.getInstance(); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Split module-level variable definition into separate files to allow + // tree-shaking on each api instance. + /** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ + const diag = DiagAPI.instance(); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ + class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NOOP_METER; + } + } + const NOOP_METER_PROVIDER = new NoopMeterProvider(); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const API_NAME$2 = 'metrics'; + /** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ + class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return registerGlobal(API_NAME$2, provider, DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return getGlobal(API_NAME$2) || NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + unregisterGlobal(API_NAME$2, DiagAPI.instance()); + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Split module-level variable definition into separate files to allow + // tree-shaking on each api instance. + /** Entrypoint for metrics API */ + const metrics = MetricsAPI.getInstance(); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * No-op implementations of {@link TextMapPropagator}. + */ + class NoopTextMapPropagator { + /** Noop inject function does nothing */ + inject(_context, _carrier) { } + /** Noop extract function does nothing and returns the input context */ + extract(context, _carrier) { + return context; + } + fields() { + return []; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + /** + * Baggage key + */ + const BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key'); + /** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ + function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; + } + /** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ + function getActiveBaggage() { + return getBaggage(ContextAPI.getInstance().active()); + } + /** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ + function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); + } + /** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ + function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const API_NAME$1 = 'propagation'; + const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); + /** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ + class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = createBaggage; + this.getBaggage = getBaggage; + this.getActiveBaggage = getActiveBaggage; + this.setBaggage = setBaggage; + this.deleteBaggage = deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return registerGlobal(API_NAME$1, propagator, DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context, carrier, setter = defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context, carrier, getter = defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + unregisterGlobal(API_NAME$1, DiagAPI.instance()); + } + _getGlobalPropagator() { + return getGlobal(API_NAME$1) || NOOP_TEXT_MAP_PROPAGATOR; + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Split module-level variable definition into separate files to allow + // tree-shaking on each api instance. + /** Entrypoint for propagation API */ + const propagation = PropagationAPI.getInstance(); + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + const API_NAME = 'trace'; + /** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ + class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider(); + this.wrapSpanContext = wrapSpanContext; + this.isSpanContextValid = isSpanContextValid; + this.deleteSpan = deleteSpan; + this.getSpan = getSpan; + this.getActiveSpan = getActiveSpan; + this.getSpanContext = getSpanContext; + this.setSpan = setSpan; + this.setSpanContext = setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return getGlobal(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); + } + /** Remove the global tracer provider */ + disable() { + unregisterGlobal(API_NAME, DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider(); + } + } + + /* + * Copyright The OpenTelemetry Authors + * + * 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 + * + * https://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. + */ + // Split module-level variable definition into separate files to allow + // tree-shaking on each api instance. + /** Entrypoint for trace API */ + const trace = TraceAPI.getInstance(); + + exports.INVALID_SPANID = INVALID_SPANID; + exports.INVALID_SPAN_CONTEXT = INVALID_SPAN_CONTEXT; + exports.INVALID_TRACEID = INVALID_TRACEID; + exports.ProxyTracer = ProxyTracer; + exports.ProxyTracerProvider = ProxyTracerProvider; + exports.ROOT_CONTEXT = ROOT_CONTEXT; + exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; + exports.context = context; + exports.createContextKey = createContextKey; + exports.createNoopMeter = createNoopMeter; + exports.defaultTextMapGetter = defaultTextMapGetter; + exports.defaultTextMapSetter = defaultTextMapSetter; + exports.diag = diag; + exports.global = global$1; + exports.isSpanContextValid = isSpanContextValid; + exports.isValidSpanId = isValidSpanId; + exports.isValidTraceId = isValidTraceId; + exports.metrics = metrics; + exports.propagation = propagation; + exports.trace = trace; + +})); diff --git a/packages/ui5-tooling-modules/test/__snap__/1ba7ed2d/axios.js b/packages/ui5-tooling-modules/test/__snap__/1ba7ed2d/axios.js index ee7f3e02..6688923e 100644 --- a/packages/ui5-tooling-modules/test/__snap__/1ba7ed2d/axios.js +++ b/packages/ui5-tooling-modules/test/__snap__/1ba7ed2d/axios.js @@ -1,4 +1,4 @@ -sap.ui.define(['exports'], (function (exports) { 'use strict'; +sap.ui.define((function () { 'use strict'; var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : @@ -226,2745 +226,2747 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; uptime: uptime }; - function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; } - // utils is a library of generic helper functions non-specific to axios + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; - const {toString: toString$1} = Object.prototype; - const {getPrototypeOf} = Object; + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - const kindOf = (cache => thing => { - const str = toString$1.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - })(Object.create(null)); + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - const kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type - }; + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); - const typeOfTest = type => thing => typeof thing === type; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - /** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * - * @returns {boolean} True if value is an Array, otherwise false - */ - const {isArray: isArray$1} = Array; + var L = 0; - /** - * Determine if a value is undefined - * - * @param {*} val The value to test - * - * @returns {boolean} True if the value is undefined, otherwise false - */ - const isUndefined = typeOfTest('undefined'); + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } - /** - * Determine if a value is a Buffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Buffer, otherwise false - */ - function isBuffer$1(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); - } + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } - /** - * Determine if a value is an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ - const isArrayBuffer = kindOfTest('ArrayBuffer'); + return arr + } + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } - /** - * Determine if a value is a view on an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ - function isArrayBufferView(val) { - let result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); } - return result; + return output.join('') } - /** - * Determine if a value is a String - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a String, otherwise false - */ - const isString = typeOfTest('string'); + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 - /** - * Determine if a value is a Function - * - * @param {*} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ - const isFunction = typeOfTest('function'); + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } - /** - * Determine if a value is a Number - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Number, otherwise false - */ - const isNumber = typeOfTest('number'); + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } - /** - * Determine if a value is an Object - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an Object, otherwise false - */ - const isObject = (thing) => thing !== null && typeof thing === 'object'; + parts.push(output); - /** - * Determine if a value is a Boolean - * - * @param {*} thing The value to test - * @returns {boolean} True if value is a Boolean, otherwise false - */ - const isBoolean = thing => thing === true || thing === false; + return parts.join('') + } - /** - * Determine if a value is a plain Object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a plain Object, otherwise false - */ - const isPlainObject = (val) => { - if (kindOf(val) !== 'object') { - return false; - } + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); - }; + i += d; - /** - * Determine if a value is a Date - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Date, otherwise false - */ - const isDate = kindOfTest('Date'); + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - /** - * Determine if a value is a File - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ - const isFile = kindOfTest('File'); + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - /** - * Determine if a value is a Blob - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Blob, otherwise false - */ - const isBlob = kindOfTest('Blob'); + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } - /** - * Determine if a value is a FileList - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ - const isFileList = kindOfTest('FileList'); + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - /** - * Determine if a value is a Stream - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Stream, otherwise false - */ - const isStream = (val) => isObject(val) && isFunction(val.pipe); + value = Math.abs(value); - /** - * Determine if a value is a FormData - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an FormData, otherwise false - */ - const isFormData = (thing) => { - let kind; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || ( - isFunction(thing.append) && ( - (kind = kindOf(thing)) === 'formdata' || - // detect form-data instance - (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') - ) - ) - ) + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString$1 = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString$1.call(arr) == '[object Array]'; }; - /** - * Determine if a value is a URLSearchParams object - * - * @param {*} val The value to test + /*! + * The buffer module from node.js, for the browser. * - * @returns {boolean} True if value is a URLSearchParams object, otherwise false + * @author Feross Aboukhadijeh + * @license MIT */ - const isURLSearchParams = kindOfTest('URLSearchParams'); + /* eslint-disable no-proto */ - const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + + var INSPECT_MAX_BYTES = 50; /** - * Trim excess whitespace off the beginning and end of a string + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) * - * @param {String} str The String to trim + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. * - * @returns {String} The String freed of excess whitespace - */ - const trim = (str) => str.trim ? - str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); - - /** - * Iterate over an Array or an Object invoking a function for each item. + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. + * Note: * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * - * @param {Boolean} [allOwnKeys = false] - * @returns {any} + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. */ - function forEach(obj, fn, {allOwnKeys = false} = {}) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; - let i; - let l; + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } - if (isArray$1(obj)) { - // Iterate over array values - for (i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; } else { - // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); } + that.length = length; } - } - function findKey(obj, key) { - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; - } - } - return null; + return that } - const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global$1) - })(); - - const isContextDefined = (context) => !isUndefined(context) && context !== _global; - /** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. * - * @returns {Object} Result of all merge properties + * The `Uint8Array` prototype remains unmodified. */ - function merge(/* obj1, obj2, obj3, ... */) { - const {caseless} = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray$1(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; - } - }; - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) } - return result; + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) } - /** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * - * @param {Boolean} [allOwnKeys] - * @returns {Object} The resulting value of object a - */ - const extend = (a, b, thisArg, {allOwnKeys}= {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }, {allOwnKeys}); - return a; + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr }; - /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * - * @returns {string} content value without BOM - */ - const stripBOM = (content) => { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') } - return content; - }; - /** - * Inherit the prototype methods from one constructor into another - * @param {function} constructor - * @param {function} superConstructor - * @param {object} [props] - * @param {object} [descriptors] - * - * @returns {void} - */ - const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, 'super', { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); - }; + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } /** - * Resolve object with deep prototype chain to a flat object - * @param {Object} sourceObj source object - * @param {Object} [destObj] - * @param {Function|Boolean} [filter] - * @param {Function} [propFilter] - * - * @returns {Object} - */ - const toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i; - let prop; - const merged = {}; + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; - destObj = destObj || {}; - // eslint-disable-next-line no-eq-null,eqeqeq - if (sourceObj == null) return destObj; + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } - return destObj; - }; + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } /** - * Determines whether a string ends with the characters of a specified string - * - * @param {String} str - * @param {String} searchString - * @param {Number} [position= 0] - * - * @returns {boolean} - */ - const endsWith = (str, searchString, position) => { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) }; + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } /** - * Returns new array from array like object or null if failed - * - * @param {*} [thing] - * - * @returns {?Array} - */ - const toArray = (thing) => { - if (!thing) return null; - if (isArray$1(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) }; - /** - * Checking if the Uint8Array exists and if it does, it returns a function that checks if the - * thing passed in is an instance of Uint8Array - * - * @param {TypedArray} - * - * @returns {Array} + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - // eslint-disable-next-line func-names - const isTypedArray = (TypedArray => { - // eslint-disable-next-line func-names - return thing => { - return TypedArray && thing instanceof TypedArray; - }; - })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; - /** - * For each entry in the object, call the function with the key and value. - * - * @param {Object} obj - The object to iterate over. - * @param {Function} fn - The function to call for each entry. - * - * @returns {void} - */ - const forEachEntry = (obj, fn) => { - const generator = obj && obj[Symbol.iterator]; + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } - const iterator = generator.call(obj); + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } - let result; + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); - while ((result = iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); } - }; - /** - * It takes a regular expression and a string, and returns an array of all the matches - * - * @param {string} regExp - The regular expression to match against. - * @param {string} str - The string to search. - * - * @returns {Array} - */ - const matchAll = (regExp, str) => { - let matches; - const arr = []; + return that + } - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; } + return that + } - return arr; - }; - - /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ - const isHTMLForm = kindOfTest('HTMLFormElement'); - - const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; - } - ); - }; - - /* Creating a function that will check if an object has a property. */ - const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer - /** - * Determine if a value is a RegExp object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a RegExp object, otherwise false - */ - const isRegExp = kindOfTest('RegExp'); + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } - const reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; - } - }); + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } - Object.defineProperties(obj, reducedDescriptors); - }; + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } - /** - * Makes all methods read-only - * @param {Object} obj - */ + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - const freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; + if (that.length === 0) { + return that } - const value = obj[name]; - - if (!isFunction(value)) return; - - descriptor.enumerable = false; + obj.copy(that, 0, 0, len); + return that + } - if ('writable' in descriptor) { - descriptor.writable = false; - return; + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) } - if (!descriptor.set) { - descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); - }; + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) } - }); - }; - - const toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - - const define = (arr) => { - arr.forEach(value => { - obj[value] = true; - }); - }; + } - isArray$1(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } - return obj; - }; + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } - const noop = () => {}; + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; - }; + if (a === b) return 0 - const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + var x = a.length; + var y = b.length; - const DIGIT = '0123456789'; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } - const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + if (x < y) return -1 + if (y < x) return 1 + return 0 }; - const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - while (size--) { - str += alphabet[Math.random() * length|0]; + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false } - - return str; }; - /** - * If the thing is a FormData object, return true, otherwise return false. - * - * @param {unknown} thing - The thing to check. - * - * @returns {boolean} - */ - function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); - } - - const toJSONObject = (obj) => { - const stack = new Array(10); - - const visit = (source, i) => { - - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray$1(source) ? [] : {}; - - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - stack[i] = undefined; + if (list.length === 0) { + return Buffer.alloc(0) + } - return target; - } + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; } + } - return source; - }; - - return visit(obj, 0); + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer }; - const isAsyncFn = kindOfTest('AsyncFunction'); - - const isThenable = (thing) => - thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); - - // original code - // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 - - const _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; } - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({source, data}) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); + var len = string.length; + if (len === 0) return 0 - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; } - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); - })( - typeof setImmediate === 'function', - isFunction(_global.postMessage) - ); - - const asap = typeof queueMicrotask !== 'undefined' ? - queueMicrotask.bind(_global) : ( typeof browser$1 !== 'undefined' && browser$1.nextTick || _setImmediate); + } + } + Buffer.byteLength = byteLength; - // ********************* + function slowToString (encoding, start, end) { + var loweredCase = false; - var utils$1 = { - isArray: isArray$1, - isArrayBuffer, - isBuffer: isBuffer$1, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - ALPHABET, - generateString, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap - }; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } + if (end === undefined || end > this.length) { + end = this.length; + } - function toByteArray (b64) { - if (!inited) { - init(); + if (end <= 0) { + return '' } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + if (!encoding) encoding = 'utf8'; - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - var L = 0; + case 'ascii': + return asciiSlice(this, start, end) - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } + case 'base64': + return base64Slice(this, start, end) - return arr - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } } - function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; } - function fromByteArray (uint8) { - if (!inited) { - init(); + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); } + return this + }; - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') } - - parts.push(output); - - return parts.join('') - } - - function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; - } - - var toString = {}.toString; - - var isArray = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; + return this }; - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - - var INSPECT_MAX_BYTES = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; - - /* - * Export kMaxLength after typed array support is determined. - */ - kMaxLength(); - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length); - } - that.length = length; - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); } - return from(this, arg, encodingOrOffset, length) - } + return this + }; - Buffer.poolSize = 8192; // not used by this implementation + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; - return arr + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 }; - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; } + return '' + }; - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) + if (start === undefined) { + start = 0; } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - }; - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) ; - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') + if (end === undefined) { + end = target ? target.length : 0; } - } - - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) + if (thisStart === undefined) { + thisStart = 0; } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) + if (thisEnd === undefined) { + thisEnd = this.length; } - return createBuffer(that, size) - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; + if (thisStart >= thisEnd && start >= end) { + return 0 } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - var actual = that.write(string, encoding); + if (this === target) return 0 - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - return that - } + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } } - return that - } - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 } - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - return that + + throw new TypeError('val must be string, number or Buffer') } - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - if (that.length === 0) { - return that + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; } + } - obj.copy(that, 0, 0, len); - return that + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; } - return fromArrayLike(that, obj) } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i } } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - Buffer.isBuffer = isBuffer; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + return -1 } - Buffer.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; } } - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength + if (length > strLen / 2) { + length = strLen / 2; } - if (typeof string !== 'string') { - string = '' + string; + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; } + return i + } - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } - Buffer.byteLength = byteLength; - function slowToString (encoding, start, end) { - var loweredCase = false; + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } - if (end === undefined || end > this.length) { - end = this.length; - } + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } - if (end <= 0) { - return '' + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - if (end <= start) { - return '' + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8'; - while (true) { + var loweredCase = false; + for (;;) { switch (encoding) { case 'hex': - return hexSlice(this, start, end) + return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': - return utf8Slice(this, start, end) + return utf8Write(this, string, offset, length) case 'ascii': - return asciiSlice(this, start, end) + return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': - return latin1Slice(this, start, end) + return latin1Write(this, string, offset, length) case 'base64': - return base64Slice(this, start, end) + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': - return utf16leSlice(this, start, end) + return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); + encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } } - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true; + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) } - Buffer.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); } - return this - }; + return res + } - Buffer.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); } - return this - }; + return ret + } - Buffer.prototype.swap64 = function swap64 () { + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; } - return this - }; - Buffer.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; + if (end < start) end = start; - Buffer.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf }; - Buffer.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } - return '' + + return val }; - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); } - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + return val + }; - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; - if (this === target) return 0 + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - if (x < y) return -1 - if (y < x) return 1 - return 0 + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) }; - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } + mul *= 0x80; - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } + return val + }; - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; } + mul *= 0x80; - throw new TypeError('val must be string, number or Buffer') - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + return val + }; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - return -1 - } + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) }; - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) }; - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) }; - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - if (length > strLen / 2) { - length = strLen / 2; + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; } - return i - } - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } + return offset + byteLength + }; - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } } - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } } - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) + objectWriteUInt32(this, value, offset, true); } + return offset + 4 + }; - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); } - if (!encoding) encoding = 'utf8'; + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + return offset + byteLength + }; - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - case 'ascii': - return asciiWrite(this, string, offset, length) + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + return offset + byteLength + }; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); } + return offset + 2 }; - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); } + return offset + 2 }; - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); } else { - return fromByteArray(buf.slice(start, end)) + objectWriteUInt32(this, value, offset, true); } - } + return offset + 4 + }; - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; - res.push(codePoint); - i += bytesPerSequence; + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); } - - return decodeCodePointsArray(res) + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 } - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000; + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res - } + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; } - return ret - } - function hexSlice (buf, start, end) { - var len = buf.length; + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + return len + }; - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; } - return out - } - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; + if (end <= start) { + return this } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - if (end < start) end = start; + if (!val) val = 0; - var newBuf; - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer.prototype; + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } } else { - var sliceLen = end - start; - newBuf = new Buffer(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; } } - return newBuf + return this }; - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } + // HELPER FUNCTIONS + // ================ - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; } + return str + } - return val - }; + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - return val - }; + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; + // valid lead + leadSurrogate = codePoint; - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; + continue + } - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + leadSurrogate = null; - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return byteArray + } - return val - }; - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; } - mul *= 0x80; + return i + } - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } - return val - }; - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; + function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; + } - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + // utils is a library of generic helper functions non-specific to axios - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; + const {toString} = Object.prototype; + const {getPrototypeOf} = Object; - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; + const kindOf = (cache => thing => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + })(Object.create(null)); - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) + const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type }; - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; + const typeOfTest = type => thing => typeof thing === type; - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; + /** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ + const {isArray} = Array; - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') + /** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ + const isUndefined = typeOfTest('undefined'); + + /** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ + function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); } - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); + /** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ + const isArrayBuffer = kindOfTest('ArrayBuffer'); + + + /** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ + function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); } + return result; + } - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + /** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ + const isString = typeOfTest('string'); + + /** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ + const isFunction = typeOfTest('function'); + + /** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ + const isNumber = typeOfTest('number'); + + /** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ + const isObject = (thing) => thing !== null && typeof thing === 'object'; + + /** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ + const isBoolean = thing => thing === true || thing === false; + + /** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ + const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; } - return offset + byteLength + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); }; - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + /** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ + const isDate = kindOfTest('Date'); + + /** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ + const isFile = kindOfTest('File'); + + /** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ + const isBlob = kindOfTest('Blob'); + + /** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ + const isFileList = kindOfTest('FileList'); - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } + /** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ + const isStream = (val) => isObject(val) && isFunction(val.pipe); - return offset + byteLength + /** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ + const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) }; - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; + /** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ + const isURLSearchParams = kindOfTest('URLSearchParams'); - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } + const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; + /** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ + const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); + /** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ + function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; } - return offset + 2 - }; - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } + let i; + let l; - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; } - return offset + 4 - }; - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; - checkInt(this, value, offset, byteLength, limit - 1, -limit); + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } } + } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; + function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } + return null; + } - return offset + byteLength - }; - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : commonjsGlobal) + })(); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + const isContextDefined = (context) => !isUndefined(context) && context !== _global; - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; + /** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ + function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; + }; - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); } - return offset + 2 - }; + return result; + } - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + /** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ + const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; }; - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); + /** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ + const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); } - return offset + 4 + return content; }; - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 + /** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ + const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); }; - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } + /** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ + const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) + return destObj; }; - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); + /** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ + const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; }; - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) + + /** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ + const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; }; - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; + /** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ + // eslint-disable-next-line func-names + const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; + })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + /** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ + const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') + const iterator = generator.call(obj); - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); } + }; - var len = end - start; - var i; + /** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ + const matchAll = (regExp, str) => { + let matches; + const arr = []; - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); } - return len + return arr; }; - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } + /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ + const isHTMLForm = kindOfTest('HTMLFormElement'); - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } + const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); + }; - if (end <= start) { - return this - } + /* Creating a function that will check if an object has a property. */ + const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + /** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ + const isRegExp = kindOfTest('RegExp'); - if (!val) val = 0; + const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; } - } + }); - return this + Object.defineProperties(obj, reducedDescriptors); }; - // HELPER FUNCTIONS - // ================ + /** + * Makes all methods read-only + * @param {Object} obj + */ - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str - } + const value = obj[name]; - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } + if (!isFunction(value)) return; - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } + descriptor.enumerable = false; - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); + }; - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } + const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; - // valid lead - leadSurrogate = codePoint; + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; - continue - } + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } + return obj; + }; - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } + const noop = () => {}; - leadSurrogate = null; + const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; + }; - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } + const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + + const DIGIT = '0123456789'; + + const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + }; + + const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; } - return bytes - } + return str; + }; - function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray + /** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ + function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); } - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break + const toJSONObject = (obj) => { + const stack = new Array(10); - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } + const visit = (source, i) => { - return byteArray - } + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; - function base64ToBytes (str) { - return toByteArray(base64clean(str)) - } + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; + stack[i] = undefined; + + return target; + } + } + + return source; + }; + + return visit(obj, 0); + }; + + const isAsyncFn = kindOfTest('AsyncFunction'); + + const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + + // original code + // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + + const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; } - return i - } - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); + })( + typeof setImmediate === 'function', + isFunction(_global.postMessage) + ); - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) - } + const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof browser$1 !== 'undefined' && browser$1.nextTick || _setImmediate); - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } + // ********************* - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) - } + var utils$1 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap + }; /** * Create an Error with the specified message, config, error code, request and response. @@ -2977,7 +2979,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {Error} The created error. */ - function AxiosError$1(message, code, config, request, response) { + function AxiosError(message, code, config, request, response) { Error.call(this); if (Error.captureStackTrace) { @@ -2997,7 +2999,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } - utils$1.inherits(AxiosError$1, Error, { + utils$1.inherits(AxiosError, Error, { toJSON: function toJSON() { return { // Standard @@ -3019,7 +3021,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }); - const prototype$1 = AxiosError$1.prototype; + const prototype$1 = AxiosError.prototype; const descriptors = {}; [ @@ -3040,11 +3042,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; descriptors[code] = {value: code}; }); - Object.defineProperties(AxiosError$1, descriptors); + Object.defineProperties(AxiosError, descriptors); Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); // eslint-disable-next-line func-names - AxiosError$1.from = (error, code, config, request, response, customProps) => { + AxiosError.from = (error, code, config, request, response, customProps) => { const axiosError = Object.create(prototype$1); utils$1.toFlatObject(error, axiosError, function filter(obj) { @@ -3053,7 +3055,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return prop !== 'isAxiosError'; }); - AxiosError$1.call(axiosError, error.message, code, config, request, response); + AxiosError.call(axiosError, error.message, code, config, request, response); axiosError.cause = error; @@ -3067,103 +3069,214 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // eslint-disable-next-line strict var httpAdapter = null; + /** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ function isVisitable(thing) { return utils$1.isPlainObject(thing) || utils$1.isArray(thing); } + + /** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ function removeBrackets(key) { - return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; } + + /** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ function renderKey(path, key, dots) { if (!path) return key; return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign token = removeBrackets(token); - return !dots && i ? "[" + token + "]" : token; - }).join(dots ? "." : ""); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); } + + /** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ function isFlatArray(arr) { return utils$1.isArray(arr) && !arr.some(isVisitable); } + const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return (/^is[A-Z]/).test(prop); + return /^is[A-Z]/.test(prop); }); - function toFormData$1(obj, formData, options) { + + /** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + + /** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ + function toFormData(obj, formData, options) { if (!utils$1.isObject(obj)) { - throw new TypeError("target must be an object"); + throw new TypeError('target must be an object'); } + + // eslint-disable-next-line no-param-reassign formData = formData || new (FormData)(); + + // eslint-disable-next-line no-param-reassign options = utils$1.toFlatObject(options, { metaTokens: true, dots: false, indexes: false }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq return !utils$1.isUndefined(source[option]); }); + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define const visitor = options.visitor || defaultVisitor; const dots = options.dots; const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { - throw new TypeError("visitor must be a function"); + throw new TypeError('visitor must be a function'); } + function convertValue(value) { - if (value === null) return ""; + if (value === null) return ''; + if (utils$1.isDate(value)) { return value.toISOString(); } + if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError$1("Blob is not supported. Use a Buffer instead."); + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } + return value; } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ function defaultVisitor(value, key, path) { let arr = value; - if (value && !path && typeof value === "object") { - if (utils$1.endsWith(key, "{}")) { + + if (value && !path && typeof value === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign value = JSON.stringify(value); - } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { + } else if ( + (utils$1.isArray(value) && isFlatArray(value)) || + ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign key = removeBrackets(key); + arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", convertValue(el)); + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); }); return false; } } + if (isVisitable(value)) { return true; } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; } + const stack = []; + const exposedHelpers = Object.assign(predicates, { defaultVisitor, convertValue, isVisitable }); + function build(value, path) { if (utils$1.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { - throw Error("Circular reference detected in " + path.join(".")); + throw Error('Circular reference detected in ' + path.join('.')); } + stack.push(value); + utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers); + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + ); + if (result === true) { build(el, path ? path.concat(key) : [key]); } }); + stack.pop(); } + if (!utils$1.isObject(obj)) { - throw new TypeError("data must be an object"); + throw new TypeError('data must be an object'); } + build(obj); + return formData; } @@ -3201,7 +3314,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function AxiosURLSearchParams(params, options) { this._pairs = []; - params && toFormData$1(params, this, options); + params && toFormData(params, this, options); } const prototype = AxiosURLSearchParams.prototype; @@ -3345,6 +3458,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } + var InterceptorManager$1 = InterceptorManager; + var transitionalDefaults = { silentJSONParsing: true, forcedJSONParsing: true, @@ -3414,8 +3529,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; var utils = /*#__PURE__*/Object.freeze({ __proto__: null, hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv, navigator: _navigator, origin: origin }); @@ -3426,7 +3541,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }; function toURLEncodedForm(data, options) { - return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({ + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ visitor: function(value, key, path, helpers) { if (platform.isNode && utils$1.isBuffer(value)) { this.append(key, value.toString('base64')); @@ -3601,7 +3716,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { const _FormData = this.env && this.env.FormData; - return toFormData$1( + return toFormData( isFileList ? {'files[]': data} : data, _FormData && new _FormData(), this.formSerializer @@ -3635,7 +3750,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { - throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response); + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } @@ -3678,6 +3793,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; defaults.headers[method] = {}; }); + var defaults$1 = defaults; + // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers const ignoreDuplicateOf = utils$1.toObjectSet([ @@ -3798,7 +3915,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); } - let AxiosHeaders$1 = class AxiosHeaders { + class AxiosHeaders { constructor(headers) { headers && this.set(headers); } @@ -4009,12 +4126,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return this; } - }; + } - AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); // reserved names hotfix - utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => { + utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` return { get: () => value, @@ -4024,7 +4141,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }); - utils$1.freezeMethods(AxiosHeaders$1); + utils$1.freezeMethods(AxiosHeaders); + + var AxiosHeaders$1 = AxiosHeaders; /** * Transform the data for a request or a response @@ -4035,7 +4154,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * @returns {*} The resulting transformed data */ function transformData(fns, response) { - const config = this || defaults; + const config = this || defaults$1; const context = response || config; const headers = AxiosHeaders$1.from(context.headers); let data = context.data; @@ -4049,7 +4168,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return data; } - function isCancel$1(value) { + function isCancel(value) { return !!(value && value.__CANCEL__); } @@ -4062,13 +4181,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {CanceledError} The created error. */ - function CanceledError$1(message, config, request) { + function CanceledError(message, config, request) { // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request); + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); this.name = 'CanceledError'; } - utils$1.inherits(CanceledError$1, AxiosError$1, { + utils$1.inherits(CanceledError, AxiosError, { __CANCEL__: true }); @@ -4086,9 +4205,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { - reject(new AxiosError$1( + reject(new AxiosError( 'Request failed with status code ' + response.status, - [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response @@ -4395,7 +4514,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {Object} New object resulting from merging config2 to config1 */ - function mergeConfig$1(config1, config2) { + function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; const config = {}; @@ -4487,7 +4606,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } var resolveConfig = (config) => { - const newConfig = mergeConfig$1({}, config); + const newConfig = mergeConfig({}, config); let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; @@ -4622,7 +4741,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return; } - reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request)); + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); // Clean up request request = null; @@ -4632,7 +4751,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error - reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request)); + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); // Clean up request request = null; @@ -4645,9 +4764,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (_config.timeoutErrorMessage) { timeoutErrorMessage = _config.timeoutErrorMessage; } - reject(new AxiosError$1( + reject(new AxiosError( timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request)); @@ -4697,7 +4816,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (!request) { return; } - reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel); + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); request.abort(); request = null; }; @@ -4711,7 +4830,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const protocol = parseProtocol(_config.url); if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config)); + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); return; } @@ -4734,13 +4853,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; aborted = true; unsubscribe(); const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err)); + controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); } }; let timer = timeout && setTimeout(() => { timer = null; - onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT)); + onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); }, timeout); const unsubscribe = () => { @@ -4764,6 +4883,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }; + var composeSignals$1 = composeSignals; + const streamChunk = function* (chunk, chunkSize) { let len = chunk.byteLength; @@ -4897,7 +5018,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : (_, config) => { - throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config); + throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); }); }); })(new Response)); @@ -4956,7 +5077,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; responseType = responseType ? (responseType + '').toLowerCase() : 'text'; - let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); let request; @@ -5058,14 +5179,14 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { throw Object.assign( - new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request), + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), { cause: err.cause || err } ) } - throw AxiosError$1.from(err, err && err.code, config, request); + throw AxiosError.from(err, err && err.code, config, request); } }); @@ -5110,7 +5231,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; if (adapter === undefined) { - throw new AxiosError$1(`Unknown adapter '${id}'`); + throw new AxiosError(`Unknown adapter '${id}'`); } } @@ -5132,7 +5253,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : 'as no adapter specified'; - throw new AxiosError$1( + throw new AxiosError( `There is no suitable adapter to dispatch the request ` + s, 'ERR_NOT_SUPPORT' ); @@ -5156,7 +5277,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } if (config.signal && config.signal.aborted) { - throw new CanceledError$1(null, config); + throw new CanceledError(null, config); } } @@ -5182,7 +5303,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; config.headers.setContentType('application/x-www-form-urlencoded', false); } - const adapter = adapters.getAdapter(config.adapter || defaults.adapter); + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); @@ -5198,7 +5319,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return response; }, function onAdapterRejection(reason) { - if (!isCancel$1(reason)) { + if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data @@ -5216,7 +5337,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); } - const VERSION$1 = "1.7.7"; + const VERSION = "1.7.7"; const validators$1 = {}; @@ -5240,15 +5361,15 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ validators$1.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { - return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return (value, opt, opts) => { if (validator === false) { - throw new AxiosError$1( + throw new AxiosError( formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError$1.ERR_DEPRECATED + AxiosError.ERR_DEPRECATED ); } @@ -5279,7 +5400,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { - throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE); + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); } const keys = Object.keys(options); let i = keys.length; @@ -5290,12 +5411,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { - throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE); + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { - throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION); + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); } } } @@ -5314,12 +5435,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @return {Axios} A new instance of Axios */ - let Axios$1 = class Axios { + class Axios { constructor(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() + request: new InterceptorManager$1(), + response: new InterceptorManager$1() }; } @@ -5368,7 +5489,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; config = configOrUrl || {}; } - config = mergeConfig$1(this.defaults, config); + config = mergeConfig(this.defaults, config); const {transitional, paramsSerializer, headers} = config; @@ -5482,17 +5603,17 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } getUri(config) { - config = mergeConfig$1(this.defaults, config); + config = mergeConfig(this.defaults, config); const fullPath = buildFullPath(config.baseURL, config.url); return buildURL(fullPath, config.params, config.paramsSerializer); } - }; + } // Provide aliases for supported request methods utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ - Axios$1.prototype[method] = function(url, config) { - return this.request(mergeConfig$1(config || {}, { + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { method, url, data: (config || {}).data @@ -5505,7 +5626,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { - return this.request(mergeConfig$1(config || {}, { + return this.request(mergeConfig(config || {}, { method, headers: isForm ? { 'Content-Type': 'multipart/form-data' @@ -5516,11 +5637,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }; } - Axios$1.prototype[method] = generateHTTPMethod(); + Axios.prototype[method] = generateHTTPMethod(); - Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true); + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); }); + var Axios$1 = Axios; + /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * @@ -5528,7 +5651,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {CancelToken} */ - let CancelToken$1 = class CancelToken { + class CancelToken { constructor(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); @@ -5576,7 +5699,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return; } - token.reason = new CanceledError$1(message, config, request); + token.reason = new CanceledError(message, config, request); resolvePromise(token.reason); }); } @@ -5649,7 +5772,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; cancel }; } - }; + } + + var CancelToken$1 = CancelToken; /** * Syntactic sugar for invoking a function and expanding an array for arguments. @@ -5672,7 +5797,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {Function} */ - function spread$1(callback) { + function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; @@ -5685,11 +5810,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ - function isAxiosError$1(payload) { + function isAxiosError(payload) { return utils$1.isObject(payload) && (payload.isAxiosError === true); } - const HttpStatusCode$1 = { + const HttpStatusCode = { Continue: 100, SwitchingProtocols: 101, Processing: 102, @@ -5755,10 +5880,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; NetworkAuthenticationRequired: 511, }; - Object.entries(HttpStatusCode$1).forEach(([key, value]) => { - HttpStatusCode$1[value] = key; + Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; }); + var HttpStatusCode$1 = HttpStatusCode; + /** * Create an instance of Axios * @@ -5778,27 +5905,27 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // Factory for creating new instances instance.create = function create(instanceConfig) { - return createInstance(mergeConfig$1(defaultConfig, instanceConfig)); + return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; return instance; } // Create the default instance to be exported - const axios = createInstance(defaults); + const axios = createInstance(defaults$1); // Expose Axios class to allow class inheritance axios.Axios = Axios$1; // Expose Cancel & CancelToken - axios.CanceledError = CanceledError$1; + axios.CanceledError = CanceledError; axios.CancelToken = CancelToken$1; - axios.isCancel = isCancel$1; - axios.VERSION = VERSION$1; - axios.toFormData = toFormData$1; + axios.isCancel = isCancel; + axios.VERSION = VERSION; + axios.toFormData = toFormData; // Expose AxiosError class - axios.AxiosError = AxiosError$1; + axios.AxiosError = AxiosError; // alias for CanceledError for backward compatibility axios.Cancel = axios.CanceledError; @@ -5808,13 +5935,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return Promise.all(promises); }; - axios.spread = spread$1; + axios.spread = spread; // Expose isAxiosError - axios.isAxiosError = isAxiosError$1; + axios.isAxiosError = isAxiosError; // Expose mergeConfig - axios.mergeConfig = mergeConfig$1; + axios.mergeConfig = mergeConfig; axios.AxiosHeaders = AxiosHeaders$1; @@ -5826,48 +5953,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; axios.default = axios; - // This module is intended to unwrap Axios default export as named. - // Keep top-level export same with static properties - // so that it can keep same with es module or cjs - const { - Axios, - AxiosError, - CanceledError, - isCancel, - CancelToken, - VERSION, - all, - Cancel, - isAxiosError, - spread, - toFormData, - AxiosHeaders, - HttpStatusCode, - formToJSON, - getAdapter, - mergeConfig - } = axios; - - let exp = axios?.default || axios || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} - - exports.Axios = Axios; - exports.AxiosError = AxiosError; - exports.AxiosHeaders = AxiosHeaders; - exports.Cancel = Cancel; - exports.CancelToken = CancelToken; - exports.CanceledError = CanceledError; - exports.HttpStatusCode = HttpStatusCode; - exports.VERSION = VERSION; - exports.all = all; - exports.default = exp; - exports.formToJSON = formToJSON; - exports.getAdapter = getAdapter; - exports.isAxiosError = isAxiosError; - exports.isCancel = isCancel; - exports.mergeConfig = mergeConfig; - exports.spread = spread; - exports.toFormData = toFormData; - - Object.defineProperty(exports, '__esModule', { value: true }); + var axios_1 = axios; + + let exp = axios_1?.default || axios_1 || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} + + return exp; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js b/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js index 5e0f1b86..0119ec42 100644 --- a/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js +++ b/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js @@ -1,234 +1,366 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; - // these aren't really private, but nor are they really useful to document - - /** - * @private - */ - class LuxonError extends Error {} - - /** - * @private - */ - class InvalidDateTimeError extends LuxonError { - constructor(reason) { - super(`Invalid DateTime: ${reason.toMessage()}`); - } + var luxon = {}; + + Object.defineProperty(luxon, "__esModule", { + value: true + }); + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if (("value" in descriptor)) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; + } + function _extends() { + _extends = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); } - - /** - * @private - */ - class InvalidIntervalError extends LuxonError { - constructor(reason) { - super(`Invalid Interval: ${reason.toMessage()}`); - } + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); } - - /** - * @private - */ - class InvalidDurationError extends LuxonError { - constructor(reason) { - super(`Invalid Duration: ${reason.toMessage()}`); - } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); } - - /** - * @private - */ - class ConflictingSpecificationError extends LuxonError {} - - /** - * @private - */ - class InvalidUnitError extends LuxonError { - constructor(unit) { - super(`Invalid unit ${unit}`); + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; } } - - /** - * @private - */ - class InvalidArgumentError extends LuxonError {} - - /** - * @private - */ - class ZoneIsAbstractError extends LuxonError { - constructor() { - super("Zone is an abstract class"); + function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; } + return _construct.apply(null, arguments); } - - /** - * @private - */ - - const n = "numeric", - s = "short", - l = "long"; - - const DATE_SHORT = { + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + _cache.set(Class, Wrapper); + } + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); + } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; + return _wrapNativeSuper(Class); + } + 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 _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 _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike) { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate 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); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (String )(input); + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + var LuxonError = (function (_Error) { + _inheritsLoose(LuxonError, _Error); + function LuxonError() { + return _Error.apply(this, arguments) || this; + } + return LuxonError; + })(_wrapNativeSuper(Error)); + var InvalidDateTimeError = (function (_LuxonError) { + _inheritsLoose(InvalidDateTimeError, _LuxonError); + function InvalidDateTimeError(reason) { + return _LuxonError.call(this, "Invalid DateTime: " + reason.toMessage()) || this; + } + return InvalidDateTimeError; + })(LuxonError); + var InvalidIntervalError = (function (_LuxonError2) { + _inheritsLoose(InvalidIntervalError, _LuxonError2); + function InvalidIntervalError(reason) { + return _LuxonError2.call(this, "Invalid Interval: " + reason.toMessage()) || this; + } + return InvalidIntervalError; + })(LuxonError); + var InvalidDurationError = (function (_LuxonError3) { + _inheritsLoose(InvalidDurationError, _LuxonError3); + function InvalidDurationError(reason) { + return _LuxonError3.call(this, "Invalid Duration: " + reason.toMessage()) || this; + } + return InvalidDurationError; + })(LuxonError); + var ConflictingSpecificationError = (function (_LuxonError4) { + _inheritsLoose(ConflictingSpecificationError, _LuxonError4); + function ConflictingSpecificationError() { + return _LuxonError4.apply(this, arguments) || this; + } + return ConflictingSpecificationError; + })(LuxonError); + var InvalidUnitError = (function (_LuxonError5) { + _inheritsLoose(InvalidUnitError, _LuxonError5); + function InvalidUnitError(unit) { + return _LuxonError5.call(this, "Invalid unit " + unit) || this; + } + return InvalidUnitError; + })(LuxonError); + var InvalidArgumentError = (function (_LuxonError6) { + _inheritsLoose(InvalidArgumentError, _LuxonError6); + function InvalidArgumentError() { + return _LuxonError6.apply(this, arguments) || this; + } + return InvalidArgumentError; + })(LuxonError); + var ZoneIsAbstractError = (function (_LuxonError7) { + _inheritsLoose(ZoneIsAbstractError, _LuxonError7); + function ZoneIsAbstractError() { + return _LuxonError7.call(this, "Zone is an abstract class") || this; + } + return ZoneIsAbstractError; + })(LuxonError); + var n = "numeric", s = "short", l = "long"; + var DATE_SHORT = { year: n, month: n, - day: n, + day: n }; - - const DATE_MED = { + var DATE_MED = { year: n, month: s, - day: n, + day: n }; - - const DATE_MED_WITH_WEEKDAY = { + var DATE_MED_WITH_WEEKDAY = { year: n, month: s, day: n, - weekday: s, + weekday: s }; - - const DATE_FULL = { + var DATE_FULL = { year: n, month: l, - day: n, + day: n }; - - const DATE_HUGE = { + var DATE_HUGE = { year: n, month: l, day: n, - weekday: l, + weekday: l }; - - const TIME_SIMPLE = { + var TIME_SIMPLE = { hour: n, - minute: n, + minute: n }; - - const TIME_WITH_SECONDS = { + var TIME_WITH_SECONDS = { hour: n, minute: n, - second: n, + second: n }; - - const TIME_WITH_SHORT_OFFSET = { + var TIME_WITH_SHORT_OFFSET = { hour: n, minute: n, second: n, - timeZoneName: s, + timeZoneName: s }; - - const TIME_WITH_LONG_OFFSET = { + var TIME_WITH_LONG_OFFSET = { hour: n, minute: n, second: n, - timeZoneName: l, + timeZoneName: l }; - - const TIME_24_SIMPLE = { + var TIME_24_SIMPLE = { hour: n, minute: n, - hourCycle: "h23", + hourCycle: "h23" }; - - const TIME_24_WITH_SECONDS = { + var TIME_24_WITH_SECONDS = { hour: n, minute: n, second: n, - hourCycle: "h23", + hourCycle: "h23" }; - - const TIME_24_WITH_SHORT_OFFSET = { + var TIME_24_WITH_SHORT_OFFSET = { hour: n, minute: n, second: n, hourCycle: "h23", - timeZoneName: s, + timeZoneName: s }; - - const TIME_24_WITH_LONG_OFFSET = { + var TIME_24_WITH_LONG_OFFSET = { hour: n, minute: n, second: n, hourCycle: "h23", - timeZoneName: l, + timeZoneName: l }; - - const DATETIME_SHORT = { + var DATETIME_SHORT = { year: n, month: n, day: n, hour: n, - minute: n, + minute: n }; - - const DATETIME_SHORT_WITH_SECONDS = { + var DATETIME_SHORT_WITH_SECONDS = { year: n, month: n, day: n, hour: n, minute: n, - second: n, + second: n }; - - const DATETIME_MED = { + var DATETIME_MED = { year: n, month: s, day: n, hour: n, - minute: n, + minute: n }; - - const DATETIME_MED_WITH_SECONDS = { + var DATETIME_MED_WITH_SECONDS = { year: n, month: s, day: n, hour: n, minute: n, - second: n, + second: n }; - - const DATETIME_MED_WITH_WEEKDAY = { + var DATETIME_MED_WITH_WEEKDAY = { year: n, month: s, day: n, weekday: s, hour: n, - minute: n, + minute: n }; - - const DATETIME_FULL = { + var DATETIME_FULL = { year: n, month: l, day: n, hour: n, minute: n, - timeZoneName: s, + timeZoneName: s }; - - const DATETIME_FULL_WITH_SECONDS = { + var DATETIME_FULL_WITH_SECONDS = { year: n, month: l, day: n, hour: n, minute: n, second: n, - timeZoneName: s, + timeZoneName: s }; - - const DATETIME_HUGE = { + var DATETIME_HUGE = { year: n, month: l, day: n, weekday: l, hour: n, minute: n, - timeZoneName: l, + timeZoneName: l }; - - const DATETIME_HUGE_WITH_SECONDS = { + var DATETIME_HUGE_WITH_SECONDS = { year: n, month: l, day: n, @@ -236,165 +368,103 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; hour: n, minute: n, second: n, - timeZoneName: l, + timeZoneName: l }; - - /** - * @interface - */ - class Zone { - /** - * The type of zone - * @abstract - * @type {string} - */ - get type() { - throw new ZoneIsAbstractError(); - } - - /** - * The name of this zone. - * @abstract - * @type {string} - */ - get name() { - throw new ZoneIsAbstractError(); - } - - /** - * The IANA name of this zone. - * Defaults to `name` if not overwritten by a subclass. - * @abstract - * @type {string} - */ - get ianaName() { - return this.name; - } - - /** - * Returns whether the offset is known to be fixed for the whole year. - * @abstract - * @type {boolean} - */ - get isUniversal() { - throw new ZoneIsAbstractError(); - } - - /** - * Returns the offset's common name (such as EST) at the specified timestamp - * @abstract - * @param {number} ts - Epoch milliseconds for which to get the name - * @param {Object} opts - Options to affect the format - * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. - * @param {string} opts.locale - What locale to return the offset name in. - * @return {string} - */ - offsetName(ts, opts) { - throw new ZoneIsAbstractError(); - } - - /** - * Returns the offset's value as a string - * @abstract - * @param {number} ts - Epoch milliseconds for which to get the offset - * @param {string} format - What style of offset to return. - * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively - * @return {string} - */ - formatOffset(ts, format) { + var Zone = (function () { + function Zone() {} + var _proto = Zone.prototype; + _proto.offsetName = function offsetName(ts, opts) { throw new ZoneIsAbstractError(); - } - - /** - * Return the offset in minutes for this zone at the specified timestamp. - * @abstract - * @param {number} ts - Epoch milliseconds for which to compute the offset - * @return {number} - */ - offset(ts) { + }; + _proto.formatOffset = function formatOffset(ts, format) { throw new ZoneIsAbstractError(); - } - - /** - * Return whether this Zone is equal to another zone - * @abstract - * @param {Zone} otherZone - the zone to compare - * @return {boolean} - */ - equals(otherZone) { + }; + _proto.offset = function offset(ts) { throw new ZoneIsAbstractError(); - } - - /** - * Return whether this Zone is valid. - * @abstract - * @type {boolean} - */ - get isValid() { + }; + _proto.equals = function equals(otherZone) { throw new ZoneIsAbstractError(); - } - } - - let singleton$1 = null; - - /** - * Represents the local zone for this JavaScript environment. - * @implements {Zone} - */ - class SystemZone extends Zone { - /** - * Get a singleton instance of the local zone - * @return {SystemZone} - */ - static get instance() { - if (singleton$1 === null) { - singleton$1 = new SystemZone(); - } - return singleton$1; - } - - /** @override **/ - get type() { - return "system"; - } - - /** @override **/ - get name() { - return new Intl.DateTimeFormat().resolvedOptions().timeZone; - } - - /** @override **/ - get isUniversal() { - return false; - } - - /** @override **/ - offsetName(ts, { format, locale }) { + }; + _createClass(Zone, [{ + key: "type", + get: function get() { + throw new ZoneIsAbstractError(); + } + }, { + key: "name", + get: function get() { + throw new ZoneIsAbstractError(); + } + }, { + key: "ianaName", + get: function get() { + return this.name; + } + }, { + key: "isUniversal", + get: function get() { + throw new ZoneIsAbstractError(); + } + }, { + key: "isValid", + get: function get() { + throw new ZoneIsAbstractError(); + } + }]); + return Zone; + })(); + var singleton$1 = null; + var SystemZone = (function (_Zone) { + _inheritsLoose(SystemZone, _Zone); + function SystemZone() { + return _Zone.apply(this, arguments) || this; + } + var _proto = SystemZone.prototype; + _proto.offsetName = function offsetName(ts, _ref) { + var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale); - } - - /** @override **/ - formatOffset(ts, format) { + }; + _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.offset(ts), format); - } - - /** @override **/ - offset(ts) { + }; + _proto.offset = function offset(ts) { return -new Date(ts).getTimezoneOffset(); - } - - /** @override **/ - equals(otherZone) { + }; + _proto.equals = function equals(otherZone) { return otherZone.type === "system"; - } - - /** @override **/ - get isValid() { - return true; - } - } - - let dtfCache = {}; + }; + _createClass(SystemZone, [{ + key: "type", + get: function get() { + return "system"; + } + }, { + key: "name", + get: function get() { + return new Intl.DateTimeFormat().resolvedOptions().timeZone; + } + }, { + key: "isUniversal", + get: function get() { + return false; + } + }, { + key: "isValid", + get: function get() { + return true; + } + }], [{ + key: "instance", + get: function get() { + if (singleton$1 === null) { + singleton$1 = new SystemZone(); + } + return singleton$1; + } + }]); + return SystemZone; + })(Zone); + var dtfCache = {}; function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat("en-US", { @@ -406,36 +476,30 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; hour: "2-digit", minute: "2-digit", second: "2-digit", - era: "short", + era: "short" }); } return dtfCache[zone]; } - - const typeToPos = { + var typeToPos = { year: 0, month: 1, day: 2, era: 3, hour: 4, minute: 5, - second: 6, + second: 6 }; - function hackyOffset(dtf, date) { - const formatted = dtf.format(date).replace(/\u200E/g, ""), - parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), - [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; + var formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = (/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/).exec(formatted), fMonth = parsed[1], fDay = parsed[2], fYear = parsed[3], fadOrBc = parsed[4], fHour = parsed[5], fMinute = parsed[6], fSecond = parsed[7]; return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; } - function partsOffset(dtf, date) { - const formatted = dtf.formatToParts(date); - const filled = []; - for (let i = 0; i < formatted.length; i++) { - const { type, value } = formatted[i]; - const pos = typeToPos[type]; - + var formatted = dtf.formatToParts(date); + var filled = []; + for (var i = 0; i < formatted.length; i++) { + var _formatted$i = formatted[i], type = _formatted$i.type, value = _formatted$i.value; + var pos = typeToPos[type]; if (type === "era") { filled[pos] = value; } else if (!isUndefined(pos)) { @@ -444,227 +508,156 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return filled; } - - let ianaZoneCache = {}; - /** - * A zone identified by an IANA identifier, like America/New_York - * @implements {Zone} - */ - class IANAZone extends Zone { - /** - * @param {string} name - Zone name - * @return {IANAZone} - */ - static create(name) { + var ianaZoneCache = {}; + var IANAZone = (function (_Zone) { + _inheritsLoose(IANAZone, _Zone); + IANAZone.create = function create(name) { if (!ianaZoneCache[name]) { ianaZoneCache[name] = new IANAZone(name); } return ianaZoneCache[name]; - } - - /** - * Reset local caches. Should only be necessary in testing scenarios. - * @return {void} - */ - static resetCache() { + }; + IANAZone.resetCache = function resetCache() { ianaZoneCache = {}; dtfCache = {}; - } - - /** - * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. - * @param {string} s - The string to check validity on - * @example IANAZone.isValidSpecifier("America/New_York") //=> true - * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false - * @deprecated For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead. - * @return {boolean} - */ - static isValidSpecifier(s) { + }; + IANAZone.isValidSpecifier = function isValidSpecifier(s) { return this.isValidZone(s); - } - - /** - * Returns whether the provided string identifies a real zone - * @param {string} zone - The string to check - * @example IANAZone.isValidZone("America/New_York") //=> true - * @example IANAZone.isValidZone("Fantasia/Castle") //=> false - * @example IANAZone.isValidZone("Sport~~blorp") //=> false - * @return {boolean} - */ - static isValidZone(zone) { + }; + IANAZone.isValidZone = function isValidZone(zone) { if (!zone) { return false; } try { - new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); + new Intl.DateTimeFormat("en-US", { + timeZone: zone + }).format(); return true; } catch (e) { return false; } - } - - constructor(name) { - super(); - /** @private **/ - this.zoneName = name; - /** @private **/ - this.valid = IANAZone.isValidZone(name); - } - - /** - * The type of zone. `iana` for all instances of `IANAZone`. - * @override - * @type {string} - */ - get type() { - return "iana"; - } - - /** - * The name of this zone (i.e. the IANA zone name). - * @override - * @type {string} - */ - get name() { - return this.zoneName; - } - - /** - * Returns whether the offset is known to be fixed for the whole year: - * Always returns false for all IANA zones. - * @override - * @type {boolean} - */ - get isUniversal() { - return false; - } - - /** - * Returns the offset's common name (such as EST) at the specified timestamp - * @override - * @param {number} ts - Epoch milliseconds for which to get the name - * @param {Object} opts - Options to affect the format - * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. - * @param {string} opts.locale - What locale to return the offset name in. - * @return {string} - */ - offsetName(ts, { format, locale }) { + }; + function IANAZone(name) { + var _this; + _this = _Zone.call(this) || this; + _this.zoneName = name; + _this.valid = IANAZone.isValidZone(name); + return _this; + } + var _proto = IANAZone.prototype; + _proto.offsetName = function offsetName(ts, _ref) { + var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale, this.name); - } - - /** - * Returns the offset's value as a string - * @override - * @param {number} ts - Epoch milliseconds for which to get the offset - * @param {string} format - What style of offset to return. - * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively - * @return {string} - */ - formatOffset(ts, format) { + }; + _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.offset(ts), format); - } - - /** - * Return the offset in minutes for this zone at the specified timestamp. - * @override - * @param {number} ts - Epoch milliseconds for which to compute the offset - * @return {number} - */ - offset(ts) { - const date = new Date(ts); - + }; + _proto.offset = function offset(ts) { + var date = new Date(ts); if (isNaN(date)) return NaN; - - const dtf = makeDTF(this.name); - let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts - ? partsOffset(dtf, date) - : hackyOffset(dtf, date); - + var dtf = makeDTF(this.name); + var _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date), year = _ref2[0], month = _ref2[1], day = _ref2[2], adOrBc = _ref2[3], hour = _ref2[4], minute = _ref2[5], second = _ref2[6]; if (adOrBc === "BC") { year = -Math.abs(year) + 1; } - - // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat - const adjustedHour = hour === 24 ? 0 : hour; - - const asUTC = objToLocalTS({ - year, - month, - day, + var adjustedHour = hour === 24 ? 0 : hour; + var asUTC = objToLocalTS({ + year: year, + month: month, + day: day, hour: adjustedHour, - minute, - second, - millisecond: 0, + minute: minute, + second: second, + millisecond: 0 }); - - let asTS = +date; - const over = asTS % 1000; + var asTS = +date; + var over = asTS % 1000; asTS -= over >= 0 ? over : 1000 + over; return (asUTC - asTS) / (60 * 1000); - } - - /** - * Return whether this Zone is equal to another zone - * @override - * @param {Zone} otherZone - the zone to compare - * @return {boolean} - */ - equals(otherZone) { + }; + _proto.equals = function equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; - } - - /** - * Return whether this Zone is valid. - * @override - * @type {boolean} - */ - get isValid() { - return this.valid; - } - } - - let intlLFCache = {}; - function getCachedLF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let dtf = intlLFCache[key]; + }; + _createClass(IANAZone, [{ + key: "type", + get: function get() { + return "iana"; + } + }, { + key: "name", + get: function get() { + return this.zoneName; + } + }, { + key: "isUniversal", + get: function get() { + return false; + } + }, { + key: "isValid", + get: function get() { + return this.valid; + } + }]); + return IANAZone; + })(Zone); + var _excluded = ["base"], _excluded2 = ["padTo", "floor"]; + var intlLFCache = {}; + function getCachedLF(locString, opts) { + if (opts === void 0) { + opts = {}; + } + var key = JSON.stringify([locString, opts]); + var dtf = intlLFCache[key]; if (!dtf) { dtf = new Intl.ListFormat(locString, opts); intlLFCache[key] = dtf; } return dtf; } - let intlDTCache = {}; - function getCachedDTF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let dtf = intlDTCache[key]; + var intlDTCache = {}; + function getCachedDTF(locString, opts) { + if (opts === void 0) { + opts = {}; + } + var key = JSON.stringify([locString, opts]); + var dtf = intlDTCache[key]; if (!dtf) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache[key] = dtf; } return dtf; } - let intlNumCache = {}; - function getCachedINF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let inf = intlNumCache[key]; + var intlNumCache = {}; + function getCachedINF(locString, opts) { + if (opts === void 0) { + opts = {}; + } + var key = JSON.stringify([locString, opts]); + var inf = intlNumCache[key]; if (!inf) { inf = new Intl.NumberFormat(locString, opts); intlNumCache[key] = inf; } return inf; } - let intlRelCache = {}; - function getCachedRTF(locString, opts = {}) { - const {base, ...cacheKeyOpts} = opts; - const key = JSON.stringify([locString, cacheKeyOpts]); - let inf = intlRelCache[key]; + var intlRelCache = {}; + function getCachedRTF(locString, opts) { + if (opts === void 0) { + opts = {}; + } + var _opts = opts; + _opts.base; + var cacheKeyOpts = _objectWithoutPropertiesLoose(_opts, _excluded); + var key = JSON.stringify([locString, cacheKeyOpts]); + var inf = intlRelCache[key]; if (!inf) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache[key] = inf; } return inf; } - let sysLocaleCache = null; + var sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; @@ -673,36 +666,36 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return sysLocaleCache; } } - let weekInfoCache = {}; + var weekInfoCache = {}; function getCachedWeekInfo(locString) { - let data = weekInfoCache[locString]; + var data = weekInfoCache[locString]; if (!data) { - const locale = new Intl.Locale(locString); + var locale = new Intl.Locale(locString); data = ("getWeekInfo" in locale) ? locale.getWeekInfo() : locale.weekInfo; weekInfoCache[locString] = data; } return data; } function parseLocaleString(localeStr) { - const xIndex = localeStr.indexOf("-x-"); + var xIndex = localeStr.indexOf("-x-"); if (xIndex !== -1) { localeStr = localeStr.substring(0, xIndex); } - const uIndex = localeStr.indexOf("-u-"); + var uIndex = localeStr.indexOf("-u-"); if (uIndex === -1) { return [localeStr]; } else { - let options; - let selectedStr; + var options; + var selectedStr; try { options = getCachedDTF(localeStr).resolvedOptions(); selectedStr = localeStr; } catch (e) { - const smaller = localeStr.substring(0, uIndex); + var smaller = localeStr.substring(0, uIndex); options = getCachedDTF(smaller).resolvedOptions(); selectedStr = smaller; } - const {numberingSystem, calendar} = options; + var _options = options, numberingSystem = _options.numberingSystem, calendar = _options.calendar; return [selectedStr, numberingSystem, calendar]; } } @@ -712,10 +705,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; localeStr += "-u"; } if (outputCalendar) { - localeStr += `-ca-${outputCalendar}`; + localeStr += "-ca-" + outputCalendar; } if (numberingSystem) { - localeStr += `-nu-${numberingSystem}`; + localeStr += "-nu-" + numberingSystem; } return localeStr; } else { @@ -723,23 +716,23 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } function mapMonths(f) { - const ms = []; - for (let i = 1; i <= 12; i++) { - const dt = DateTime.utc(2009, i, 1); + var ms = []; + for (var i = 1; i <= 12; i++) { + var dt = DateTime.utc(2009, i, 1); ms.push(f(dt)); } return ms; } function mapWeekdays(f) { - const ms = []; - for (let i = 1; i <= 7; i++) { - const dt = DateTime.utc(2016, 11, 13 + i); + var ms = []; + for (var i = 1; i <= 7; i++) { + var dt = DateTime.utc(2016, 11, 13 + i); ms.push(f(dt)); } return ms; } function listStuff(loc, length, englishFn, intlFn) { - const mode = loc.listingMode(); + var mode = loc.listingMode(); if (mode === "error") { return null; } else if (mode === "en") { @@ -755,40 +748,43 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; } } - class PolyNumberFormatter { - constructor(intl, forceSimple, opts) { + var PolyNumberFormatter = (function () { + function PolyNumberFormatter(intl, forceSimple, opts) { this.padTo = opts.padTo || 0; this.floor = opts.floor || false; - const {padTo, floor, ...otherOpts} = opts; + opts.padTo; + opts.floor; + var otherOpts = _objectWithoutPropertiesLoose(opts, _excluded2); if (!forceSimple || Object.keys(otherOpts).length > 0) { - const intlOpts = { - useGrouping: false, - ...opts - }; + var intlOpts = _extends({ + useGrouping: false + }, opts); if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo; this.inf = getCachedINF(intl, intlOpts); } } - format(i) { + var _proto = PolyNumberFormatter.prototype; + _proto.format = function format(i) { if (this.inf) { - const fixed = this.floor ? Math.floor(i) : i; + var fixed = this.floor ? Math.floor(i) : i; return this.inf.format(fixed); } else { - const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); - return padStart(fixed, this.padTo); + var _fixed = this.floor ? Math.floor(i) : roundTo(i, 3); + return padStart(_fixed, this.padTo); } - } - } - class PolyDateFormatter { - constructor(dt, intl, opts) { + }; + return PolyNumberFormatter; + })(); + var PolyDateFormatter = (function () { + function PolyDateFormatter(dt, intl, opts) { this.opts = opts; this.originalZone = undefined; - let z = undefined; + var z = undefined; if (this.opts.timeZone) { this.dt = dt; } else if (dt.zone.type === "fixed") { - const gmtOffset = -1 * (dt.offset / 60); - const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; + var gmtOffset = -1 * (dt.offset / 60); + var offsetZ = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset; if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { z = offsetZ; this.dt = dt; @@ -811,95 +807,103 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); this.originalZone = dt.zone; } - const intlOpts = { - ...this.opts - }; + var intlOpts = _extends({}, this.opts); intlOpts.timeZone = intlOpts.timeZone || z; this.dtf = getCachedDTF(intl, intlOpts); } - format() { + var _proto2 = PolyDateFormatter.prototype; + _proto2.format = function format() { if (this.originalZone) { - return this.formatToParts().map(({value}) => value).join(""); + return this.formatToParts().map(function (_ref) { + var value = _ref.value; + return value; + }).join(""); } return this.dtf.format(this.dt.toJSDate()); - } - formatToParts() { - const parts = this.dtf.formatToParts(this.dt.toJSDate()); + }; + _proto2.formatToParts = function formatToParts() { + var _this = this; + var parts = this.dtf.formatToParts(this.dt.toJSDate()); if (this.originalZone) { - return parts.map(part => { + return parts.map(function (part) { if (part.type === "timeZoneName") { - const offsetName = this.originalZone.offsetName(this.dt.ts, { - locale: this.dt.locale, - format: this.opts.timeZoneName + var offsetName = _this.originalZone.offsetName(_this.dt.ts, { + locale: _this.dt.locale, + format: _this.opts.timeZoneName }); - return { - ...part, + return _extends({}, part, { value: offsetName - }; + }); } else { return part; } }); } return parts; - } - resolvedOptions() { + }; + _proto2.resolvedOptions = function resolvedOptions() { return this.dtf.resolvedOptions(); - } - } - class PolyRelFormatter { - constructor(intl, isEnglish, opts) { - this.opts = { - style: "long", - ...opts - }; + }; + return PolyDateFormatter; + })(); + var PolyRelFormatter = (function () { + function PolyRelFormatter(intl, isEnglish, opts) { + this.opts = _extends({ + style: "long" + }, opts); if (!isEnglish && hasRelative()) { this.rtf = getCachedRTF(intl, opts); } } - format(count, unit) { + var _proto3 = PolyRelFormatter.prototype; + _proto3.format = function format(count, unit) { if (this.rtf) { return this.rtf.format(count, unit); } else { return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); } - } - formatToParts(count, unit) { + }; + _proto3.formatToParts = function formatToParts(count, unit) { if (this.rtf) { return this.rtf.formatToParts(count, unit); } else { return []; } - } - } - const fallbackWeekSettings = { + }; + return PolyRelFormatter; + })(); + var fallbackWeekSettings = { firstDay: 1, minimalDays: 4, weekend: [6, 7] }; - class Locale { - static fromOpts(opts) { + var Locale = (function () { + Locale.fromOpts = function fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN); - } - static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) { - const specifiedLocale = locale || Settings.defaultLocale; - const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); - const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; - const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; - const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; + }; + Locale.create = function create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN) { + if (defaultToEN === void 0) { + defaultToEN = false; + } + var specifiedLocale = locale || Settings.defaultLocale; + var localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); + var numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; + var outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; + var weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); - } - static resetCache() { + }; + Locale.resetCache = function resetCache() { sysLocaleCache = null; intlDTCache = {}; intlNumCache = {}; intlRelCache = {}; - } - static fromObject({locale, numberingSystem, outputCalendar, weekSettings} = {}) { + }; + Locale.fromObject = function fromObject(_temp) { + var _ref2 = _temp === void 0 ? {} : _temp, locale = _ref2.locale, numberingSystem = _ref2.numberingSystem, outputCalendar = _ref2.outputCalendar, weekSettings = _ref2.weekSettings; return Locale.create(locale, numberingSystem, outputCalendar, weekSettings); - } - constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { - const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); + }; + function Locale(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { + var _parseLocaleString = parseLocaleString(locale), parsedLocale = _parseLocaleString[0], parsedNumberingSystem = _parseLocaleString[1], parsedOutputCalendar = _parseLocaleString[2]; this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; @@ -918,53 +922,62 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; this.specifiedLocale = specifiedLocale; this.fastNumbersCached = null; } - get fastNumbers() { - if (this.fastNumbersCached == null) { - this.fastNumbersCached = supportsFastNumbers(this); - } - return this.fastNumbersCached; - } - listingMode() { - const isActuallyEn = this.isEnglish(); - const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); + var _proto4 = Locale.prototype; + _proto4.listingMode = function listingMode() { + var isActuallyEn = this.isEnglish(); + var hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); return isActuallyEn && hasNoWeirdness ? "en" : "intl"; - } - clone(alts) { + }; + _proto4.clone = function clone(alts) { if (!alts || Object.getOwnPropertyNames(alts).length === 0) { return this; } else { return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false); } - } - redefaultToEN(alts = {}) { - return this.clone({ - ...alts, + }; + _proto4.redefaultToEN = function redefaultToEN(alts) { + if (alts === void 0) { + alts = {}; + } + return this.clone(_extends({}, alts, { defaultToEN: true - }); - } - redefaultToSystem(alts = {}) { - return this.clone({ - ...alts, + })); + }; + _proto4.redefaultToSystem = function redefaultToSystem(alts) { + if (alts === void 0) { + alts = {}; + } + return this.clone(_extends({}, alts, { defaultToEN: false - }); - } - months(length, format = false) { - return listStuff(this, length, months, () => { - const intl = format ? { + })); + }; + _proto4.months = function months$1(length, format) { + var _this2 = this; + if (format === void 0) { + format = false; + } + return listStuff(this, length, months, function () { + var intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; - if (!this.monthsCache[formatStr][length]) { - this.monthsCache[formatStr][length] = mapMonths(dt => this.extract(dt, intl, "month")); + if (!_this2.monthsCache[formatStr][length]) { + _this2.monthsCache[formatStr][length] = mapMonths(function (dt) { + return _this2.extract(dt, intl, "month"); + }); } - return this.monthsCache[formatStr][length]; + return _this2.monthsCache[formatStr][length]; }); - } - weekdays(length, format = false) { - return listStuff(this, length, weekdays, () => { - const intl = format ? { + }; + _proto4.weekdays = function weekdays$1(length, format) { + var _this3 = this; + if (format === void 0) { + format = false; + } + return listStuff(this, length, weekdays, function () { + var intl = format ? { weekday: length, year: "numeric", month: "long", @@ -972,55 +985,79 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } : { weekday: length }, formatStr = format ? "format" : "standalone"; - if (!this.weekdaysCache[formatStr][length]) { - this.weekdaysCache[formatStr][length] = mapWeekdays(dt => this.extract(dt, intl, "weekday")); + if (!_this3.weekdaysCache[formatStr][length]) { + _this3.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) { + return _this3.extract(dt, intl, "weekday"); + }); } - return this.weekdaysCache[formatStr][length]; + return _this3.weekdaysCache[formatStr][length]; }); - } - meridiems() { - return listStuff(this, undefined, () => meridiems, () => { - if (!this.meridiemCache) { - const intl = { + }; + _proto4.meridiems = function meridiems$1() { + var _this4 = this; + return listStuff(this, undefined, function () { + return meridiems; + }, function () { + if (!_this4.meridiemCache) { + var intl = { hour: "numeric", hourCycle: "h12" }; - this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(dt => this.extract(dt, intl, "dayperiod")); + _this4.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) { + return _this4.extract(dt, intl, "dayperiod"); + }); } - return this.meridiemCache; + return _this4.meridiemCache; }); - } - eras(length) { - return listStuff(this, length, eras, () => { - const intl = { + }; + _proto4.eras = function eras$1(length) { + var _this5 = this; + return listStuff(this, length, eras, function () { + var intl = { era: length }; - if (!this.eraCache[length]) { - this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt => this.extract(dt, intl, "era")); + if (!_this5.eraCache[length]) { + _this5.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(function (dt) { + return _this5.extract(dt, intl, "era"); + }); } - return this.eraCache[length]; + return _this5.eraCache[length]; + }); + }; + _proto4.extract = function extract(dt, intlOpts, field) { + var df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find(function (m) { + return m.type.toLowerCase() === field; }); - } - extract(dt, intlOpts, field) { - const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find(m => m.type.toLowerCase() === field); return matching ? matching.value : null; - } - numberFormatter(opts = {}) { + }; + _proto4.numberFormatter = function numberFormatter(opts) { + if (opts === void 0) { + opts = {}; + } return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); - } - dtFormatter(dt, intlOpts = {}) { + }; + _proto4.dtFormatter = function dtFormatter(dt, intlOpts) { + if (intlOpts === void 0) { + intlOpts = {}; + } return new PolyDateFormatter(dt, this.intl, intlOpts); - } - relFormatter(opts = {}) { + }; + _proto4.relFormatter = function relFormatter(opts) { + if (opts === void 0) { + opts = {}; + } return new PolyRelFormatter(this.intl, this.isEnglish(), opts); - } - listFormatter(opts = {}) { + }; + _proto4.listFormatter = function listFormatter(opts) { + if (opts === void 0) { + opts = {}; + } return getCachedLF(this.intl, opts); - } - isEnglish() { + }; + _proto4.isEnglish = function isEnglish() { return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); - } - getWeekSettings() { + }; + _proto4.getWeekSettings = function getWeekSettings() { if (this.weekSettings) { return this.weekSettings; } else if (!hasLocaleWeekInfo()) { @@ -1028,276 +1065,191 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { return getCachedWeekInfo(this.locale); } - } - getStartOfWeek() { + }; + _proto4.getStartOfWeek = function getStartOfWeek() { return this.getWeekSettings().firstDay; - } - getMinDaysInFirstWeek() { + }; + _proto4.getMinDaysInFirstWeek = function getMinDaysInFirstWeek() { return this.getWeekSettings().minimalDays; - } - getWeekendDays() { + }; + _proto4.getWeekendDays = function getWeekendDays() { return this.getWeekSettings().weekend; - } - equals(other) { + }; + _proto4.equals = function equals(other) { return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; - } - toString() { - return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`; - } - } - - let singleton = null; - - /** - * A zone with a fixed offset (meaning no DST) - * @implements {Zone} - */ - class FixedOffsetZone extends Zone { - /** - * Get a singleton instance of UTC - * @return {FixedOffsetZone} - */ - static get utcInstance() { - if (singleton === null) { - singleton = new FixedOffsetZone(0); - } - return singleton; - } - - /** - * Get an instance with a specified offset - * @param {number} offset - The offset in minutes - * @return {FixedOffsetZone} - */ - static instance(offset) { + }; + _proto4.toString = function toString() { + return "Locale(" + this.locale + ", " + this.numberingSystem + ", " + this.outputCalendar + ")"; + }; + _createClass(Locale, [{ + key: "fastNumbers", + get: function get() { + if (this.fastNumbersCached == null) { + this.fastNumbersCached = supportsFastNumbers(this); + } + return this.fastNumbersCached; + } + }]); + return Locale; + })(); + var singleton = null; + var FixedOffsetZone = (function (_Zone) { + _inheritsLoose(FixedOffsetZone, _Zone); + FixedOffsetZone.instance = function instance(offset) { return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); - } - - /** - * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" - * @param {string} s - The offset string to parse - * @example FixedOffsetZone.parseSpecifier("UTC+6") - * @example FixedOffsetZone.parseSpecifier("UTC+06") - * @example FixedOffsetZone.parseSpecifier("UTC-6:00") - * @return {FixedOffsetZone} - */ - static parseSpecifier(s) { + }; + FixedOffsetZone.parseSpecifier = function parseSpecifier(s) { if (s) { - const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); if (r) { return new FixedOffsetZone(signedOffset(r[1], r[2])); } } return null; - } - - constructor(offset) { - super(); - /** @private **/ - this.fixed = offset; - } - - /** - * The type of zone. `fixed` for all instances of `FixedOffsetZone`. - * @override - * @type {string} - */ - get type() { - return "fixed"; - } - - /** - * The name of this zone. - * All fixed zones' names always start with "UTC" (plus optional offset) - * @override - * @type {string} - */ - get name() { - return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; - } - - /** - * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn` - * - * @override - * @type {string} - */ - get ianaName() { - if (this.fixed === 0) { - return "Etc/UTC"; - } else { - return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; - } - } - - /** - * Returns the offset's common name at the specified timestamp. - * - * For fixed offset zones this equals to the zone name. - * @override - */ - offsetName() { + }; + function FixedOffsetZone(offset) { + var _this; + _this = _Zone.call(this) || this; + _this.fixed = offset; + return _this; + } + var _proto = FixedOffsetZone.prototype; + _proto.offsetName = function offsetName() { return this.name; - } - - /** - * Returns the offset's value as a string - * @override - * @param {number} ts - Epoch milliseconds for which to get the offset - * @param {string} format - What style of offset to return. - * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively - * @return {string} - */ - formatOffset(ts, format) { + }; + _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.fixed, format); - } - - /** - * Returns whether the offset is known to be fixed for the whole year: - * Always returns true for all fixed offset zones. - * @override - * @type {boolean} - */ - get isUniversal() { - return true; - } - - /** - * Return the offset in minutes for this zone at the specified timestamp. - * - * For fixed offset zones, this is constant and does not depend on a timestamp. - * @override - * @return {number} - */ - offset() { + }; + _proto.offset = function offset() { return this.fixed; - } - - /** - * Return whether this Zone is equal to another zone (i.e. also fixed and same offset) - * @override - * @param {Zone} otherZone - the zone to compare - * @return {boolean} - */ - equals(otherZone) { + }; + _proto.equals = function equals(otherZone) { return otherZone.type === "fixed" && otherZone.fixed === this.fixed; - } - - /** - * Return whether this Zone is valid: - * All fixed offset zones are valid. - * @override - * @type {boolean} - */ - get isValid() { - return true; - } - } - - /** - * A zone that failed to parse. You should never need to instantiate this. - * @implements {Zone} - */ - class InvalidZone extends Zone { - constructor(zoneName) { - super(); - /** @private */ - this.zoneName = zoneName; - } - - /** @override **/ - get type() { - return "invalid"; - } - - /** @override **/ - get name() { - return this.zoneName; - } - - /** @override **/ - get isUniversal() { - return false; - } - - /** @override **/ - offsetName() { + }; + _createClass(FixedOffsetZone, [{ + key: "type", + get: function get() { + return "fixed"; + } + }, { + key: "name", + get: function get() { + return this.fixed === 0 ? "UTC" : "UTC" + formatOffset(this.fixed, "narrow"); + } + }, { + key: "ianaName", + get: function get() { + if (this.fixed === 0) { + return "Etc/UTC"; + } else { + return "Etc/GMT" + formatOffset(-this.fixed, "narrow"); + } + } + }, { + key: "isUniversal", + get: function get() { + return true; + } + }, { + key: "isValid", + get: function get() { + return true; + } + }], [{ + key: "utcInstance", + get: function get() { + if (singleton === null) { + singleton = new FixedOffsetZone(0); + } + return singleton; + } + }]); + return FixedOffsetZone; + })(Zone); + var InvalidZone = (function (_Zone) { + _inheritsLoose(InvalidZone, _Zone); + function InvalidZone(zoneName) { + var _this; + _this = _Zone.call(this) || this; + _this.zoneName = zoneName; + return _this; + } + var _proto = InvalidZone.prototype; + _proto.offsetName = function offsetName() { return null; - } - - /** @override **/ - formatOffset() { + }; + _proto.formatOffset = function formatOffset() { return ""; - } - - /** @override **/ - offset() { + }; + _proto.offset = function offset() { return NaN; - } - - /** @override **/ - equals() { - return false; - } - - /** @override **/ - get isValid() { + }; + _proto.equals = function equals() { return false; - } - } - - /** - * @private - */ - - + }; + _createClass(InvalidZone, [{ + key: "type", + get: function get() { + return "invalid"; + } + }, { + key: "name", + get: function get() { + return this.zoneName; + } + }, { + key: "isUniversal", + get: function get() { + return false; + } + }, { + key: "isValid", + get: function get() { + return false; + } + }]); + return InvalidZone; + })(Zone); function normalizeZone(input, defaultZone) { if (isUndefined(input) || input === null) { return defaultZone; } else if (input instanceof Zone) { return input; } else if (isString(input)) { - const lowered = input.toLowerCase(); - if (lowered === "default") return defaultZone; - else if (lowered === "local" || lowered === "system") return SystemZone.instance; - else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance; - else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); + var lowered = input.toLowerCase(); + if (lowered === "default") return defaultZone; else if (lowered === "local" || lowered === "system") return SystemZone.instance; else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance; else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); } else if (isNumber(input)) { return FixedOffsetZone.instance(input); - } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { - // This is dumb, but the instanceof check above doesn't seem to really work - // so we're duck checking it + } else if (typeof input === "object" && ("offset" in input) && typeof input.offset === "function") { return input; } else { return new InvalidZone(input); } } - - const numberingSystems = { - arab: "[\u0660-\u0669]", - arabext: "[\u06F0-\u06F9]", - bali: "[\u1B50-\u1B59]", - beng: "[\u09E6-\u09EF]", - deva: "[\u0966-\u096F]", - fullwide: "[\uFF10-\uFF19]", - gujr: "[\u0AE6-\u0AEF]", + var numberingSystems = { + arab: "[٠-٩]", + arabext: "[۰-۹]", + bali: "[᭐-᭙]", + beng: "[০-৯]", + deva: "[०-९]", + fullwide: "[0-9]", + gujr: "[૦-૯]", hanidec: "[〇|一|二|三|四|五|六|七|八|九]", - khmr: "[\u17E0-\u17E9]", - knda: "[\u0CE6-\u0CEF]", - laoo: "[\u0ED0-\u0ED9]", - limb: "[\u1946-\u194F]", - mlym: "[\u0D66-\u0D6F]", - mong: "[\u1810-\u1819]", - mymr: "[\u1040-\u1049]", - orya: "[\u0B66-\u0B6F]", - tamldec: "[\u0BE6-\u0BEF]", - telu: "[\u0C66-\u0C6F]", - thai: "[\u0E50-\u0E59]", - tibt: "[\u0F20-\u0F29]", - latn: "\\d", + khmr: "[០-៩]", + knda: "[೦-೯]", + laoo: "[໐-໙]", + limb: "[᥆-᥏]", + mlym: "[൦-൯]", + mong: "[᠐-᠙]", + mymr: "[၀-၉]", + orya: "[୦-୯]", + tamldec: "[௦-௯]", + telu: "[౦-౯]", + thai: "[๐-๙]", + tibt: "[༠-༩]", + latn: "\\d" }; - - const numberingSystemsUTF16 = { + var numberingSystemsUTF16 = { arab: [1632, 1641], arabext: [1776, 1785], bali: [6992, 7001], @@ -1316,23 +1268,20 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; tamldec: [3046, 3055], telu: [3174, 3183], thai: [3664, 3673], - tibt: [3872, 3881], + tibt: [3872, 3881] }; - - const hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); - + var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); function parseDigits(str) { - let value = parseInt(str, 10); + var value = parseInt(str, 10); if (isNaN(value)) { value = ""; - for (let i = 0; i < str.length; i++) { - const code = str.charCodeAt(i); - + for (var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); if (str[i].search(numberingSystems.hanidec) !== -1) { value += hanidecChars.indexOf(str[i]); } else { - for (const key in numberingSystemsUTF16) { - const [min, max] = numberingSystemsUTF16[key]; + for (var key in numberingSystemsUTF16) { + var _numberingSystemsUTF = numberingSystemsUTF16[key], min = _numberingSystemsUTF[0], max = _numberingSystemsUTF[1]; if (code >= min && code <= max) { value += code - min; } @@ -1344,262 +1293,153 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return value; } } - - // cache of {numberingSystem: {append: regex}} - let digitRegexCache = {}; + var digitRegexCache = {}; function resetDigitRegexCache() { digitRegexCache = {}; } - - function digitRegex({ numberingSystem }, append = "") { - const ns = numberingSystem || "latn"; - + function digitRegex(_ref, append) { + var numberingSystem = _ref.numberingSystem; + if (append === void 0) { + append = ""; + } + var ns = numberingSystem || "latn"; if (!digitRegexCache[ns]) { digitRegexCache[ns] = {}; } if (!digitRegexCache[ns][append]) { - digitRegexCache[ns][append] = new RegExp(`${numberingSystems[ns]}${append}`); + digitRegexCache[ns][append] = new RegExp("" + numberingSystems[ns] + append); } - return digitRegexCache[ns][append]; } - - let now = () => Date.now(), - defaultZone = "system", - defaultLocale = null, - defaultNumberingSystem = null, - defaultOutputCalendar = null, - twoDigitCutoffYear = 60, - throwOnInvalid, - defaultWeekSettings = null; - - /** - * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here. - */ - class Settings { - /** - * Get the callback for returning the current timestamp. - * @type {function} - */ - static get now() { - return now; - } - - /** - * Set the callback for returning the current timestamp. - * The function should return a number, which will be interpreted as an Epoch millisecond count - * @type {function} - * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future - * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time - */ - static set now(n) { - now = n; - } - - /** - * Set the default time zone to create DateTimes in. Does not affect existing instances. - * Use the value "system" to reset this value to the system's time zone. - * @type {string} - */ - static set defaultZone(zone) { - defaultZone = zone; - } - - /** - * Get the default time zone object currently used to create DateTimes. Does not affect existing instances. - * The default value is the system's time zone (the one set on the machine that runs this code). - * @type {Zone} - */ - static get defaultZone() { - return normalizeZone(defaultZone, SystemZone.instance); - } - - /** - * Get the default locale to create DateTimes with. Does not affect existing instances. - * @type {string} - */ - static get defaultLocale() { - return defaultLocale; - } - - /** - * Set the default locale to create DateTimes with. Does not affect existing instances. - * @type {string} - */ - static set defaultLocale(locale) { - defaultLocale = locale; - } - - /** - * Get the default numbering system to create DateTimes with. Does not affect existing instances. - * @type {string} - */ - static get defaultNumberingSystem() { - return defaultNumberingSystem; - } - - /** - * Set the default numbering system to create DateTimes with. Does not affect existing instances. - * @type {string} - */ - static set defaultNumberingSystem(numberingSystem) { - defaultNumberingSystem = numberingSystem; - } - - /** - * Get the default output calendar to create DateTimes with. Does not affect existing instances. - * @type {string} - */ - static get defaultOutputCalendar() { - return defaultOutputCalendar; - } - - /** - * Set the default output calendar to create DateTimes with. Does not affect existing instances. - * @type {string} - */ - static set defaultOutputCalendar(outputCalendar) { - defaultOutputCalendar = outputCalendar; - } - - /** - * @typedef {Object} WeekSettings - * @property {number} firstDay - * @property {number} minimalDays - * @property {number[]} weekend - */ - - /** - * @return {WeekSettings|null} - */ - static get defaultWeekSettings() { - return defaultWeekSettings; - } - - /** - * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and - * how many days are required in the first week of a year. - * Does not affect existing instances. - * - * @param {WeekSettings|null} weekSettings - */ - static set defaultWeekSettings(weekSettings) { - defaultWeekSettings = validateWeekSettings(weekSettings); - } - - /** - * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx. - * @type {number} - */ - static get twoDigitCutoffYear() { - return twoDigitCutoffYear; - } - - /** - * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx. - * @type {number} - * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century - * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century - * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950 - * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50 - * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50 - */ - static set twoDigitCutoffYear(cutoffYear) { - twoDigitCutoffYear = cutoffYear % 100; - } - - /** - * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals - * @type {boolean} - */ - static get throwOnInvalid() { - return throwOnInvalid; - } - - /** - * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals - * @type {boolean} - */ - static set throwOnInvalid(t) { - throwOnInvalid = t; - } - - /** - * Reset Luxon's global caches. Should only be necessary in testing scenarios. - * @return {void} - */ - static resetCaches() { + var now = function now() { + return Date.now(); + }, defaultZone = "system", defaultLocale = null, defaultNumberingSystem = null, defaultOutputCalendar = null, twoDigitCutoffYear = 60, throwOnInvalid, defaultWeekSettings = null; + var Settings = (function () { + function Settings() {} + Settings.resetCaches = function resetCaches() { Locale.resetCache(); IANAZone.resetCache(); DateTime.resetCache(); resetDigitRegexCache(); - } - } - - class Invalid { - constructor(reason, explanation) { + }; + _createClass(Settings, null, [{ + key: "now", + get: function get() { + return now; + }, + set: function set(n) { + now = n; + } + }, { + key: "defaultZone", + get: function get() { + return normalizeZone(defaultZone, SystemZone.instance); + }, + set: function set(zone) { + defaultZone = zone; + } + }, { + key: "defaultLocale", + get: function get() { + return defaultLocale; + }, + set: function set(locale) { + defaultLocale = locale; + } + }, { + key: "defaultNumberingSystem", + get: function get() { + return defaultNumberingSystem; + }, + set: function set(numberingSystem) { + defaultNumberingSystem = numberingSystem; + } + }, { + key: "defaultOutputCalendar", + get: function get() { + return defaultOutputCalendar; + }, + set: function set(outputCalendar) { + defaultOutputCalendar = outputCalendar; + } + }, { + key: "defaultWeekSettings", + get: function get() { + return defaultWeekSettings; + }, + set: function set(weekSettings) { + defaultWeekSettings = validateWeekSettings(weekSettings); + } + }, { + key: "twoDigitCutoffYear", + get: function get() { + return twoDigitCutoffYear; + }, + set: function set(cutoffYear) { + twoDigitCutoffYear = cutoffYear % 100; + } + }, { + key: "throwOnInvalid", + get: function get() { + return throwOnInvalid; + }, + set: function set(t) { + throwOnInvalid = t; + } + }]); + return Settings; + })(); + var Invalid = (function () { + function Invalid(reason, explanation) { this.reason = reason; this.explanation = explanation; } - - toMessage() { + var _proto = Invalid.prototype; + _proto.toMessage = function toMessage() { if (this.explanation) { - return `${this.reason}: ${this.explanation}`; + return this.reason + ": " + this.explanation; } else { return this.reason; } - } - } - - const nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], - leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; - + }; + return Invalid; + })(); + var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; function unitOutOfRange(unit, value) { - return new Invalid( - "unit out of range", - `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid` - ); + return new Invalid("unit out of range", "you specified " + value + " (of type " + typeof value + ") as a " + unit + ", which is invalid"); } - function dayOfWeek(year, month, day) { - const d = new Date(Date.UTC(year, month - 1, day)); - + var d = new Date(Date.UTC(year, month - 1, day)); if (year < 100 && year >= 0) { d.setUTCFullYear(d.getUTCFullYear() - 1900); } - - const js = d.getUTCDay(); - + var js = d.getUTCDay(); return js === 0 ? 7 : js; } - function computeOrdinal(year, month, day) { return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; } - function uncomputeOrdinal(year, ordinal) { - const table = isLeapYear(year) ? leapLadder : nonLeapLadder, - month0 = table.findIndex((i) => i < ordinal), - day = ordinal - table[month0]; - return { month: month0 + 1, day }; + var table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex(function (i) { + return i < ordinal; + }), day = ordinal - table[month0]; + return { + month: month0 + 1, + day: day + }; } - function isoWeekdayToLocal(isoWeekday, startOfWeek) { - return ((isoWeekday - startOfWeek + 7) % 7) + 1; + return (isoWeekday - startOfWeek + 7) % 7 + 1; } - - /** - * @private - */ - - function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) { - const { year, month, day } = gregObj, - ordinal = computeOrdinal(year, month, day), - weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); - - let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), - weekYear; - + function gregorianToWeek(gregObj, minDaysInFirstWeek, startOfWeek) { + if (minDaysInFirstWeek === void 0) { + minDaysInFirstWeek = 4; + } + if (startOfWeek === void 0) { + startOfWeek = 1; + } + var year = gregObj.year, month = gregObj.month, day = gregObj.day, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); + var weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear; if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); @@ -1609,18 +1449,21 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { weekYear = year; } - - return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; + return _extends({ + weekYear: weekYear, + weekNumber: weekNumber, + weekday: weekday + }, timeObject(gregObj)); } - - function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) { - const { weekYear, weekNumber, weekday } = weekData, - weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), - yearInDays = daysInYear(weekYear); - - let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, - year; - + function weekToGregorian(weekData, minDaysInFirstWeek, startOfWeek) { + if (minDaysInFirstWeek === void 0) { + minDaysInFirstWeek = 4; + } + if (startOfWeek === void 0) { + startOfWeek = 1; + } + var weekYear = weekData.weekYear, weekNumber = weekData.weekNumber, weekday = weekData.weekday, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear); + var ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year; if (ordinal < 1) { year = weekYear - 1; ordinal += daysInYear(year); @@ -1630,42 +1473,36 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { year = weekYear; } - - const { month, day } = uncomputeOrdinal(year, ordinal); - return { year, month, day, ...timeObject(weekData) }; + var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal.month, day = _uncomputeOrdinal.day; + return _extends({ + year: year, + month: month, + day: day + }, timeObject(weekData)); } - function gregorianToOrdinal(gregData) { - const { year, month, day } = gregData; - const ordinal = computeOrdinal(year, month, day); - return { year, ordinal, ...timeObject(gregData) }; + var year = gregData.year, month = gregData.month, day = gregData.day; + var ordinal = computeOrdinal(year, month, day); + return _extends({ + year: year, + ordinal: ordinal + }, timeObject(gregData)); } - function ordinalToGregorian(ordinalData) { - const { year, ordinal } = ordinalData; - const { month, day } = uncomputeOrdinal(year, ordinal); - return { year, month, day, ...timeObject(ordinalData) }; + var year = ordinalData.year, ordinal = ordinalData.ordinal; + var _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal2.month, day = _uncomputeOrdinal2.day; + return _extends({ + year: year, + month: month, + day: day + }, timeObject(ordinalData)); } - - /** - * Check if local week units like localWeekday are used in obj. - * If so, validates that they are not mixed with ISO week units and then copies them to the normal week unit properties. - * Modifies obj in-place! - * @param obj the object values - */ function usesLocalWeekValues(obj, loc) { - const hasLocaleWeekData = - !isUndefined(obj.localWeekday) || - !isUndefined(obj.localWeekNumber) || - !isUndefined(obj.localWeekYear); + var hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); if (hasLocaleWeekData) { - const hasIsoWeekData = - !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); - + var hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); if (hasIsoWeekData) { - throw new ConflictingSpecificationError( - "Cannot mix locale-based week fields with ISO-based week fields" - ); + throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields"); } if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday; if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber; @@ -1675,22 +1512,23 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; delete obj.localWeekYear; return { minDaysInFirstWeek: loc.getMinDaysInFirstWeek(), - startOfWeek: loc.getStartOfWeek(), + startOfWeek: loc.getStartOfWeek() }; } else { - return { minDaysInFirstWeek: 4, startOfWeek: 1 }; + return { + minDaysInFirstWeek: 4, + startOfWeek: 1 + }; } } - - function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) { - const validYear = isInteger(obj.weekYear), - validWeek = integerBetween( - obj.weekNumber, - 1, - weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek) - ), - validWeekday = integerBetween(obj.weekday, 1, 7); - + function hasInvalidWeekData(obj, minDaysInFirstWeek, startOfWeek) { + if (minDaysInFirstWeek === void 0) { + minDaysInFirstWeek = 4; + } + if (startOfWeek === void 0) { + startOfWeek = 1; + } + var validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)), validWeekday = integerBetween(obj.weekday, 1, 7); if (!validYear) { return unitOutOfRange("weekYear", obj.weekYear); } else if (!validWeek) { @@ -1699,23 +1537,16 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return unitOutOfRange("weekday", obj.weekday); } else return false; } - function hasInvalidOrdinalData(obj) { - const validYear = isInteger(obj.year), - validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); - + var validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validOrdinal) { return unitOutOfRange("ordinal", obj.ordinal); } else return false; } - function hasInvalidGregorianData(obj) { - const validYear = isInteger(obj.year), - validMonth = integerBetween(obj.month, 1, 12), - validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); - + var validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validMonth) { @@ -1724,16 +1555,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return unitOutOfRange("day", obj.day); } else return false; } - function hasInvalidTimeData(obj) { - const { hour, minute, second, millisecond } = obj; - const validHour = - integerBetween(hour, 0, 23) || - (hour === 24 && minute === 0 && second === 0 && millisecond === 0), - validMinute = integerBetween(minute, 0, 59), - validSecond = integerBetween(second, 0, 59), - validMillisecond = integerBetween(millisecond, 0, 999); - + var hour = obj.hour, minute = obj.minute, second = obj.second, millisecond = obj.millisecond; + var validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); if (!validHour) { return unitOutOfRange("hour", hour); } else if (!validMinute) { @@ -1744,42 +1568,21 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return unitOutOfRange("millisecond", millisecond); } else return false; } - - /* - This is just a junk drawer, containing anything used across multiple classes. - Because Luxon is small(ish), this should stay small and we won't worry about splitting - it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area. - */ - - - /** - * @private - */ - - // TYPES - function isUndefined(o) { return typeof o === "undefined"; } - function isNumber(o) { return typeof o === "number"; } - function isInteger(o) { return typeof o === "number" && o % 1 === 0; } - function isString(o) { return typeof o === "string"; } - function isDate(o) { return Object.prototype.toString.call(o) === "[object Date]"; } - - // CAPABILITIES - function hasRelative() { try { return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; @@ -1787,31 +1590,22 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return false; } } - function hasLocaleWeekInfo() { try { - return ( - typeof Intl !== "undefined" && - !!Intl.Locale && - ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype) - ); + return typeof Intl !== "undefined" && !!Intl.Locale && (("weekInfo" in Intl.Locale.prototype) || ("getWeekInfo" in Intl.Locale.prototype)); } catch (e) { return false; } } - - // OBJECTS AND ARRAYS - function maybeArray(thing) { return Array.isArray(thing) ? thing : [thing]; } - function bestBy(arr, by, compare) { if (arr.length === 0) { return undefined; } - return arr.reduce((best, next) => { - const pair = [by(next), next]; + return arr.reduce(function (best, next) { + var pair = [by(next), next]; if (!best) { return pair; } else if (compare(best[0], pair[0]) === best[0]) { @@ -1821,54 +1615,45 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }, null)[1]; } - function pick(obj, keys) { - return keys.reduce((a, k) => { + return keys.reduce(function (a, k) { a[k] = obj[k]; return a; }, {}); } - function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } - function validateWeekSettings(settings) { if (settings == null) { return null; } else if (typeof settings !== "object") { throw new InvalidArgumentError("Week settings must be an object"); } else { - if ( - !integerBetween(settings.firstDay, 1, 7) || - !integerBetween(settings.minimalDays, 1, 7) || - !Array.isArray(settings.weekend) || - settings.weekend.some((v) => !integerBetween(v, 1, 7)) - ) { + if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some(function (v) { + return !integerBetween(v, 1, 7); + })) { throw new InvalidArgumentError("Invalid week settings"); } return { firstDay: settings.firstDay, minimalDays: settings.minimalDays, - weekend: Array.from(settings.weekend), + weekend: Array.from(settings.weekend) }; } } - - // NUMBERS AND STRINGS - function integerBetween(thing, bottom, top) { return isInteger(thing) && thing >= bottom && thing <= top; } - - // x % n but takes the sign of n instead of x function floorMod(x, n) { return x - n * Math.floor(x / n); } - - function padStart(input, n = 2) { - const isNeg = input < 0; - let padded; + function padStart(input, n) { + if (n === void 0) { + n = 2; + } + var isNeg = input < 0; + var padded; if (isNeg) { padded = "-" + ("" + -input).padStart(n, "0"); } else { @@ -1876,7 +1661,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return padded; } - function parseInteger(string) { if (isUndefined(string) || string === null || string === "") { return undefined; @@ -1884,7 +1668,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return parseInt(string, 10); } } - function parseFloating(string) { if (isUndefined(string) || string === null || string === "") { return undefined; @@ -1892,217 +1675,137 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return parseFloat(string); } } - function parseMillis(fraction) { - // Return undefined (instead of 0) in these cases, where fraction is not set if (isUndefined(fraction) || fraction === null || fraction === "") { return undefined; } else { - const f = parseFloat("0." + fraction) * 1000; + var f = parseFloat("0." + fraction) * 1000; return Math.floor(f); } } - - function roundTo(number, digits, towardZero = false) { - const factor = 10 ** digits, - rounder = towardZero ? Math.trunc : Math.round; + function roundTo(number, digits, towardZero) { + if (towardZero === void 0) { + towardZero = false; + } + var factor = Math.pow(10, digits), rounder = towardZero ? Math.trunc : Math.round; return rounder(number * factor) / factor; } - - // DATE BASICS - function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } - function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } - function daysInMonth(year, month) { - const modMonth = floorMod(month - 1, 12) + 1, - modYear = year + (month - modMonth) / 12; - + var modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; if (modMonth === 2) { return isLeapYear(modYear) ? 29 : 28; } else { return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; } } - - // convert a calendar object to a local timestamp (epoch, but with the offset baked in) function objToLocalTS(obj) { - let d = Date.UTC( - obj.year, - obj.month - 1, - obj.day, - obj.hour, - obj.minute, - obj.second, - obj.millisecond - ); - - // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that + var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); if (obj.year < 100 && obj.year >= 0) { d = new Date(d); - // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not - // so if obj.year is in 99, but obj.day makes it roll over into year 100, - // the calculations done by Date.UTC are using year 2000 - which is incorrect d.setUTCFullYear(obj.year, obj.month - 1, obj.day); } return +d; } - - // adapted from moment.js: https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/src/lib/units/week-calendar-utils.js function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) { - const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); + var fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); return -fwdlw + minDaysInFirstWeek - 1; } - - function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { - const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); - const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); + function weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek) { + if (minDaysInFirstWeek === void 0) { + minDaysInFirstWeek = 4; + } + if (startOfWeek === void 0) { + startOfWeek = 1; + } + var weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); + var weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7; } - function untruncateYear(year) { if (year > 99) { return year; } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year; } - - // PARSING - - function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) { - const date = new Date(ts), - intlOpts = { - hourCycle: "h23", - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - }; - + function parseZoneInfo(ts, offsetFormat, locale, timeZone) { + if (timeZone === void 0) { + timeZone = null; + } + var date = new Date(ts), intlOpts = { + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit" + }; if (timeZone) { intlOpts.timeZone = timeZone; } - - const modified = { timeZoneName: offsetFormat, ...intlOpts }; - - const parsed = new Intl.DateTimeFormat(locale, modified) - .formatToParts(date) - .find((m) => m.type.toLowerCase() === "timezonename"); + var modified = _extends({ + timeZoneName: offsetFormat + }, intlOpts); + var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) { + return m.type.toLowerCase() === "timezonename"; + }); return parsed ? parsed.value : null; } - - // signedOffset('-5', '30') -> -330 function signedOffset(offHourStr, offMinuteStr) { - let offHour = parseInt(offHourStr, 10); - - // don't || this because we want to preserve -0 + var offHour = parseInt(offHourStr, 10); if (Number.isNaN(offHour)) { offHour = 0; } - - const offMin = parseInt(offMinuteStr, 10) || 0, - offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + var offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; return offHour * 60 + offMinSigned; } - - // COERCION - function asNumber(value) { - const numericValue = Number(value); - if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) - throw new InvalidArgumentError(`Invalid unit value ${value}`); + var numericValue = Number(value); + if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) throw new InvalidArgumentError("Invalid unit value " + value); return numericValue; } - function normalizeObject(obj, normalizer) { - const normalized = {}; - for (const u in obj) { + var normalized = {}; + for (var u in obj) { if (hasOwnProperty(obj, u)) { - const v = obj[u]; + var v = obj[u]; if (v === undefined || v === null) continue; normalized[normalizer(u)] = asNumber(v); } } return normalized; } - - /** - * Returns the offset's value as a string - * @param {number} ts - Epoch milliseconds for which to get the offset - * @param {string} format - What style of offset to return. - * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively - * @return {string} - */ function formatOffset(offset, format) { - const hours = Math.trunc(Math.abs(offset / 60)), - minutes = Math.trunc(Math.abs(offset % 60)), - sign = offset >= 0 ? "+" : "-"; - + var hours = Math.trunc(Math.abs(offset / 60)), minutes = Math.trunc(Math.abs(offset % 60)), sign = offset >= 0 ? "+" : "-"; switch (format) { case "short": - return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`; + return "" + sign + padStart(hours, 2) + ":" + padStart(minutes, 2); case "narrow": - return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; + return "" + sign + hours + (minutes > 0 ? ":" + minutes : ""); case "techie": - return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`; + return "" + sign + padStart(hours, 2) + padStart(minutes, 2); default: - throw new RangeError(`Value format ${format} is out of range for property format`); + throw new RangeError("Value format " + format + " is out of range for property format"); } } - function timeObject(obj) { return pick(obj, ["hour", "minute", "second", "millisecond"]); } - - /** - * @private - */ - - const monthsLong = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - ]; - - const monthsShort = [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", - ]; - - const monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; - + var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; function months(length) { switch (length) { case "narrow": - return [...monthsNarrow]; + return [].concat(monthsNarrow); case "short": - return [...monthsShort]; + return [].concat(monthsShort); case "long": - return [...monthsLong]; + return [].concat(monthsLong); case "numeric": return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; case "2-digit": @@ -2111,75 +1814,59 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return null; } } - - const weekdaysLong = [ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday", - ]; - - const weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; - - const weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; - + var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; + var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; function weekdays(length) { switch (length) { case "narrow": - return [...weekdaysNarrow]; + return [].concat(weekdaysNarrow); case "short": - return [...weekdaysShort]; + return [].concat(weekdaysShort); case "long": - return [...weekdaysLong]; + return [].concat(weekdaysLong); case "numeric": return ["1", "2", "3", "4", "5", "6", "7"]; default: return null; } } - - const meridiems = ["AM", "PM"]; - - const erasLong = ["Before Christ", "Anno Domini"]; - - const erasShort = ["BC", "AD"]; - - const erasNarrow = ["B", "A"]; - + var meridiems = ["AM", "PM"]; + var erasLong = ["Before Christ", "Anno Domini"]; + var erasShort = ["BC", "AD"]; + var erasNarrow = ["B", "A"]; function eras(length) { switch (length) { case "narrow": - return [...erasNarrow]; + return [].concat(erasNarrow); case "short": - return [...erasShort]; + return [].concat(erasShort); case "long": - return [...erasLong]; + return [].concat(erasLong); default: return null; } } - function meridiemForDateTime(dt) { return meridiems[dt.hour < 12 ? 0 : 1]; } - function weekdayForDateTime(dt, length) { return weekdays(length)[dt.weekday - 1]; } - function monthForDateTime(dt, length) { return months(length)[dt.month - 1]; } - function eraForDateTime(dt, length) { return eras(length)[dt.year < 0 ? 0 : 1]; } - - function formatRelativeTime(unit, count, numeric = "always", narrow = false) { - const units = { + function formatRelativeTime(unit, count, numeric, narrow) { + if (numeric === void 0) { + numeric = "always"; + } + if (narrow === void 0) { + narrow = false; + } + var units = { years: ["year", "yr."], quarters: ["quarter", "qtr."], months: ["month", "mo."], @@ -2187,40 +1874,27 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; days: ["day", "day", "days"], hours: ["hour", "hr."], minutes: ["minute", "min."], - seconds: ["second", "sec."], + seconds: ["second", "sec."] }; - - const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; - + var lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; if (numeric === "auto" && lastable) { - const isDay = unit === "days"; + var isDay = unit === "days"; switch (count) { case 1: - return isDay ? "tomorrow" : `next ${units[unit][0]}`; + return isDay ? "tomorrow" : "next " + units[unit][0]; case -1: - return isDay ? "yesterday" : `last ${units[unit][0]}`; + return isDay ? "yesterday" : "last " + units[unit][0]; case 0: - return isDay ? "today" : `this ${units[unit][0]}`; + return isDay ? "today" : "this " + units[unit][0]; } } - - const isInPast = Object.is(count, -0) || count < 0, - fmtValue = Math.abs(count), - singular = fmtValue === 1, - lilUnits = units[unit], - fmtUnit = narrow - ? singular - ? lilUnits[1] - : lilUnits[2] || lilUnits[1] - : singular - ? units[unit][0] - : unit; - return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; + var isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; + return isInPast ? fmtValue + " " + fmtUnit + " ago" : "in " + fmtValue + " " + fmtUnit; } - function stringifyTokens(splits, tokenToString) { - let s = ""; - for (const token of splits) { + var s = ""; + for (var _iterator = _createForOfIteratorHelperLoose(splits), _step; !(_step = _iterator()).done; ) { + var token = _step.value; if (token.literal) { s += token.val; } else { @@ -2229,8 +1903,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return s; } - - const macroTokenToFormatOpts = { + var _macroTokenToFormatOpts = { D: DATE_SHORT, DD: DATE_MED, DDD: DATE_FULL, @@ -2250,31 +1923,26 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; F: DATETIME_SHORT_WITH_SECONDS, FF: DATETIME_MED_WITH_SECONDS, FFF: DATETIME_FULL_WITH_SECONDS, - FFFF: DATETIME_HUGE_WITH_SECONDS, + FFFF: DATETIME_HUGE_WITH_SECONDS }; - - /** - * @private - */ - - class Formatter { - static create(locale, opts = {}) { + var Formatter = (function () { + Formatter.create = function create(locale, opts) { + if (opts === void 0) { + opts = {}; + } return new Formatter(locale, opts); - } - - static parseFormat(fmt) { - // white-space is always considered a literal in user-provided formats - // the " " token has a special meaning (see unitForToken) - - let current = null, - currentFull = "", - bracketed = false; - const splits = []; - for (let i = 0; i < fmt.length; i++) { - const c = fmt.charAt(i); + }; + Formatter.parseFormat = function parseFormat(fmt) { + var current = null, currentFull = "", bracketed = false; + var splits = []; + for (var i = 0; i < fmt.length; i++) { + var c = fmt.charAt(i); if (c === "'") { if (currentFull.length > 0) { - splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + splits.push({ + literal: bracketed || (/^\s+$/).test(currentFull), + val: currentFull + }); } current = null; currentFull = ""; @@ -2285,493 +1953,436 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; currentFull += c; } else { if (currentFull.length > 0) { - splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); + splits.push({ + literal: (/^\s+$/).test(currentFull), + val: currentFull + }); } currentFull = c; current = c; } } - if (currentFull.length > 0) { - splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + splits.push({ + literal: bracketed || (/^\s+$/).test(currentFull), + val: currentFull + }); } - return splits; - } - - static macroTokenToFormatOpts(token) { - return macroTokenToFormatOpts[token]; - } - - constructor(locale, formatOpts) { + }; + Formatter.macroTokenToFormatOpts = function macroTokenToFormatOpts(token) { + return _macroTokenToFormatOpts[token]; + }; + function Formatter(locale, formatOpts) { this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } - - formatWithSystemDefault(dt, opts) { + var _proto = Formatter.prototype; + _proto.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } - const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts }); + var df = this.systemLoc.dtFormatter(dt, _extends({}, this.opts, opts)); return df.format(); - } - - dtFormatter(dt, opts = {}) { - return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); - } - - formatDateTime(dt, opts) { + }; + _proto.dtFormatter = function dtFormatter(dt, opts) { + if (opts === void 0) { + opts = {}; + } + return this.loc.dtFormatter(dt, _extends({}, this.opts, opts)); + }; + _proto.formatDateTime = function formatDateTime(dt, opts) { return this.dtFormatter(dt, opts).format(); - } - - formatDateTimeParts(dt, opts) { + }; + _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) { return this.dtFormatter(dt, opts).formatToParts(); - } - - formatInterval(interval, opts) { - const df = this.dtFormatter(interval.start, opts); + }; + _proto.formatInterval = function formatInterval(interval, opts) { + var df = this.dtFormatter(interval.start, opts); return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); - } - - resolvedOptions(dt, opts) { + }; + _proto.resolvedOptions = function resolvedOptions(dt, opts) { return this.dtFormatter(dt, opts).resolvedOptions(); - } - - num(n, p = 0) { - // we get some perf out of doing this here, annoyingly + }; + _proto.num = function num(n, p) { + if (p === void 0) { + p = 0; + } if (this.opts.forceSimple) { return padStart(n, p); } - - const opts = { ...this.opts }; - + var opts = _extends({}, this.opts); if (p > 0) { opts.padTo = p; } - return this.loc.numberFormatter(opts).format(n); - } - - formatDateTimeFromString(dt, fmt) { - const knownEnglish = this.loc.listingMode() === "en", - useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", - string = (opts, extract) => this.loc.extract(dt, opts, extract), - formatOffset = (opts) => { - if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { - return "Z"; - } - - return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; - }, - meridiem = () => - knownEnglish - ? meridiemForDateTime(dt) - : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), - month = (length, standalone) => - knownEnglish - ? monthForDateTime(dt, length) - : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), - weekday = (length, standalone) => - knownEnglish - ? weekdayForDateTime(dt, length) - : string( - standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, - "weekday" - ), - maybeMacro = (token) => { - const formatOpts = Formatter.macroTokenToFormatOpts(token); - if (formatOpts) { - return this.formatWithSystemDefault(dt, formatOpts); - } else { - return token; - } - }, - era = (length) => - knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), - tokenToString = (token) => { - // Where possible: https://cldr.unicode.org/translation/date-time/date-time-symbols - switch (token) { - // ms - case "S": - return this.num(dt.millisecond); - case "u": - // falls through - case "SSS": - return this.num(dt.millisecond, 3); - // seconds - case "s": - return this.num(dt.second); - case "ss": - return this.num(dt.second, 2); - // fractional seconds - case "uu": - return this.num(Math.floor(dt.millisecond / 10), 2); - case "uuu": - return this.num(Math.floor(dt.millisecond / 100)); - // minutes - case "m": - return this.num(dt.minute); - case "mm": - return this.num(dt.minute, 2); - // hours - case "h": - return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); - case "hh": - return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); - case "H": - return this.num(dt.hour); - case "HH": - return this.num(dt.hour, 2); - // offset - case "Z": - // like +6 - return formatOffset({ format: "narrow", allowZ: this.opts.allowZ }); - case "ZZ": - // like +06:00 - return formatOffset({ format: "short", allowZ: this.opts.allowZ }); - case "ZZZ": - // like +0600 - return formatOffset({ format: "techie", allowZ: this.opts.allowZ }); - case "ZZZZ": - // like EST - return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); - case "ZZZZZ": - // like Eastern Standard Time - return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); - // zone - case "z": - // like America/New_York - return dt.zoneName; - // meridiems - case "a": - return meridiem(); - // dates - case "d": - return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); - case "dd": - return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); - // weekdays - standalone - case "c": - // like 1 - return this.num(dt.weekday); - case "ccc": - // like 'Tues' - return weekday("short", true); - case "cccc": - // like 'Tuesday' - return weekday("long", true); - case "ccccc": - // like 'T' - return weekday("narrow", true); - // weekdays - format - case "E": - // like 1 - return this.num(dt.weekday); - case "EEE": - // like 'Tues' - return weekday("short", false); - case "EEEE": - // like 'Tuesday' - return weekday("long", false); - case "EEEEE": - // like 'T' - return weekday("narrow", false); - // months - standalone - case "L": - // like 1 - return useDateTimeFormatter - ? string({ month: "numeric", day: "numeric" }, "month") - : this.num(dt.month); - case "LL": - // like 01, doesn't seem to work - return useDateTimeFormatter - ? string({ month: "2-digit", day: "numeric" }, "month") - : this.num(dt.month, 2); - case "LLL": - // like Jan - return month("short", true); - case "LLLL": - // like January - return month("long", true); - case "LLLLL": - // like J - return month("narrow", true); - // months - format - case "M": - // like 1 - return useDateTimeFormatter - ? string({ month: "numeric" }, "month") - : this.num(dt.month); - case "MM": - // like 01 - return useDateTimeFormatter - ? string({ month: "2-digit" }, "month") - : this.num(dt.month, 2); - case "MMM": - // like Jan - return month("short", false); - case "MMMM": - // like January - return month("long", false); - case "MMMMM": - // like J - return month("narrow", false); - // years - case "y": - // like 2014 - return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); - case "yy": - // like 14 - return useDateTimeFormatter - ? string({ year: "2-digit" }, "year") - : this.num(dt.year.toString().slice(-2), 2); - case "yyyy": - // like 0012 - return useDateTimeFormatter - ? string({ year: "numeric" }, "year") - : this.num(dt.year, 4); - case "yyyyyy": - // like 000012 - return useDateTimeFormatter - ? string({ year: "numeric" }, "year") - : this.num(dt.year, 6); - // eras - case "G": - // like AD - return era("short"); - case "GG": - // like Anno Domini - return era("long"); - case "GGGGG": - return era("narrow"); - case "kk": - return this.num(dt.weekYear.toString().slice(-2), 2); - case "kkkk": - return this.num(dt.weekYear, 4); - case "W": - return this.num(dt.weekNumber); - case "WW": - return this.num(dt.weekNumber, 2); - case "n": - return this.num(dt.localWeekNumber); - case "nn": - return this.num(dt.localWeekNumber, 2); - case "ii": - return this.num(dt.localWeekYear.toString().slice(-2), 2); - case "iiii": - return this.num(dt.localWeekYear, 4); - case "o": - return this.num(dt.ordinal); - case "ooo": - return this.num(dt.ordinal, 3); - case "q": - // like 1 - return this.num(dt.quarter); - case "qq": - // like 01 - return this.num(dt.quarter, 2); - case "X": - return this.num(Math.floor(dt.ts / 1000)); - case "x": - return this.num(dt.ts); - default: - return maybeMacro(token); - } - }; - + }; + _proto.formatDateTimeFromString = function formatDateTimeFromString(dt, fmt) { + var _this = this; + var knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = function string(opts, extract) { + return _this.loc.extract(dt, opts, extract); + }, formatOffset = function formatOffset(opts) { + if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { + return "Z"; + } + return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; + }, meridiem = function meridiem() { + return knownEnglish ? meridiemForDateTime(dt) : string({ + hour: "numeric", + hourCycle: "h12" + }, "dayperiod"); + }, month = function month(length, standalone) { + return knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { + month: length + } : { + month: length, + day: "numeric" + }, "month"); + }, weekday = function weekday(length, standalone) { + return knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? { + weekday: length + } : { + weekday: length, + month: "long", + day: "numeric" + }, "weekday"); + }, maybeMacro = function maybeMacro(token) { + var formatOpts = Formatter.macroTokenToFormatOpts(token); + if (formatOpts) { + return _this.formatWithSystemDefault(dt, formatOpts); + } else { + return token; + } + }, era = function era(length) { + return knownEnglish ? eraForDateTime(dt, length) : string({ + era: length + }, "era"); + }, tokenToString = function tokenToString(token) { + switch (token) { + case "S": + return _this.num(dt.millisecond); + case "u": + case "SSS": + return _this.num(dt.millisecond, 3); + case "s": + return _this.num(dt.second); + case "ss": + return _this.num(dt.second, 2); + case "uu": + return _this.num(Math.floor(dt.millisecond / 10), 2); + case "uuu": + return _this.num(Math.floor(dt.millisecond / 100)); + case "m": + return _this.num(dt.minute); + case "mm": + return _this.num(dt.minute, 2); + case "h": + return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); + case "hh": + return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); + case "H": + return _this.num(dt.hour); + case "HH": + return _this.num(dt.hour, 2); + case "Z": + return formatOffset({ + format: "narrow", + allowZ: _this.opts.allowZ + }); + case "ZZ": + return formatOffset({ + format: "short", + allowZ: _this.opts.allowZ + }); + case "ZZZ": + return formatOffset({ + format: "techie", + allowZ: _this.opts.allowZ + }); + case "ZZZZ": + return dt.zone.offsetName(dt.ts, { + format: "short", + locale: _this.loc.locale + }); + case "ZZZZZ": + return dt.zone.offsetName(dt.ts, { + format: "long", + locale: _this.loc.locale + }); + case "z": + return dt.zoneName; + case "a": + return meridiem(); + case "d": + return useDateTimeFormatter ? string({ + day: "numeric" + }, "day") : _this.num(dt.day); + case "dd": + return useDateTimeFormatter ? string({ + day: "2-digit" + }, "day") : _this.num(dt.day, 2); + case "c": + return _this.num(dt.weekday); + case "ccc": + return weekday("short", true); + case "cccc": + return weekday("long", true); + case "ccccc": + return weekday("narrow", true); + case "E": + return _this.num(dt.weekday); + case "EEE": + return weekday("short", false); + case "EEEE": + return weekday("long", false); + case "EEEEE": + return weekday("narrow", false); + case "L": + return useDateTimeFormatter ? string({ + month: "numeric", + day: "numeric" + }, "month") : _this.num(dt.month); + case "LL": + return useDateTimeFormatter ? string({ + month: "2-digit", + day: "numeric" + }, "month") : _this.num(dt.month, 2); + case "LLL": + return month("short", true); + case "LLLL": + return month("long", true); + case "LLLLL": + return month("narrow", true); + case "M": + return useDateTimeFormatter ? string({ + month: "numeric" + }, "month") : _this.num(dt.month); + case "MM": + return useDateTimeFormatter ? string({ + month: "2-digit" + }, "month") : _this.num(dt.month, 2); + case "MMM": + return month("short", false); + case "MMMM": + return month("long", false); + case "MMMMM": + return month("narrow", false); + case "y": + return useDateTimeFormatter ? string({ + year: "numeric" + }, "year") : _this.num(dt.year); + case "yy": + return useDateTimeFormatter ? string({ + year: "2-digit" + }, "year") : _this.num(dt.year.toString().slice(-2), 2); + case "yyyy": + return useDateTimeFormatter ? string({ + year: "numeric" + }, "year") : _this.num(dt.year, 4); + case "yyyyyy": + return useDateTimeFormatter ? string({ + year: "numeric" + }, "year") : _this.num(dt.year, 6); + case "G": + return era("short"); + case "GG": + return era("long"); + case "GGGGG": + return era("narrow"); + case "kk": + return _this.num(dt.weekYear.toString().slice(-2), 2); + case "kkkk": + return _this.num(dt.weekYear, 4); + case "W": + return _this.num(dt.weekNumber); + case "WW": + return _this.num(dt.weekNumber, 2); + case "n": + return _this.num(dt.localWeekNumber); + case "nn": + return _this.num(dt.localWeekNumber, 2); + case "ii": + return _this.num(dt.localWeekYear.toString().slice(-2), 2); + case "iiii": + return _this.num(dt.localWeekYear, 4); + case "o": + return _this.num(dt.ordinal); + case "ooo": + return _this.num(dt.ordinal, 3); + case "q": + return _this.num(dt.quarter); + case "qq": + return _this.num(dt.quarter, 2); + case "X": + return _this.num(Math.floor(dt.ts / 1000)); + case "x": + return _this.num(dt.ts); + default: + return maybeMacro(token); + } + }; return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); - } - - formatDurationFromString(dur, fmt) { - const tokenToField = (token) => { - switch (token[0]) { - case "S": - return "millisecond"; - case "s": - return "second"; - case "m": - return "minute"; - case "h": - return "hour"; - case "d": - return "day"; - case "w": - return "week"; - case "M": - return "month"; - case "y": - return "year"; - default: - return null; - } - }, - tokenToString = (lildur) => (token) => { - const mapped = tokenToField(token); + }; + _proto.formatDurationFromString = function formatDurationFromString(dur, fmt) { + var _this2 = this; + var tokenToField = function tokenToField(token) { + switch (token[0]) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + return "hour"; + case "d": + return "day"; + case "w": + return "week"; + case "M": + return "month"; + case "y": + return "year"; + default: + return null; + } + }, tokenToString = function tokenToString(lildur) { + return function (token) { + var mapped = tokenToField(token); if (mapped) { - return this.num(lildur.get(mapped), token.length); + return _this2.num(lildur.get(mapped), token.length); } else { return token; } - }, - tokens = Formatter.parseFormat(fmt), - realTokens = tokens.reduce( - (found, { literal, val }) => (literal ? found : found.concat(val)), - [] - ), - collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)); + }; + }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce(function (found, _ref) { + var literal = _ref.literal, val = _ref.val; + return literal ? found : found.concat(val); + }, []), collapsed = dur.shiftTo.apply(dur, realTokens.map(tokenToField).filter(function (t) { + return t; + })); return stringifyTokens(tokens, tokenToString(collapsed)); - } - } - - /* - * This file handles parsing for well-specified formats. Here's how it works: - * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match. - * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object - * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence. - * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors. - * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions. - * Some extractions are super dumb and simpleParse and fromStrings help DRY them. - */ - - const ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; - - function combineRegexes(...regexes) { - const full = regexes.reduce((f, r) => f + r.source, ""); - return RegExp(`^${full}$`); - } - - function combineExtractors(...extractors) { - return (m) => - extractors - .reduce( - ([mergedVals, mergedZone, cursor], ex) => { - const [val, zone, next] = ex(m, cursor); - return [{ ...mergedVals, ...val }, zone || mergedZone, next]; - }, - [{}, null, 1] - ) - .slice(0, 2); + }; + return Formatter; + })(); + var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; + function combineRegexes() { + for (var _len = arguments.length, regexes = new Array(_len), _key = 0; _key < _len; _key++) { + regexes[_key] = arguments[_key]; + } + var full = regexes.reduce(function (f, r) { + return f + r.source; + }, ""); + return RegExp("^" + full + "$"); + } + function combineExtractors() { + for (var _len2 = arguments.length, extractors = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + extractors[_key2] = arguments[_key2]; + } + return function (m) { + return extractors.reduce(function (_ref, ex) { + var mergedVals = _ref[0], mergedZone = _ref[1], cursor = _ref[2]; + var _ex = ex(m, cursor), val = _ex[0], zone = _ex[1], next = _ex[2]; + return [_extends({}, mergedVals, val), zone || mergedZone, next]; + }, [{}, null, 1]).slice(0, 2); + }; } - - function parse(s, ...patterns) { + function parse(s) { if (s == null) { return [null, null]; } - - for (const [regex, extractor] of patterns) { - const m = regex.exec(s); + for (var _len3 = arguments.length, patterns = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + patterns[_key3 - 1] = arguments[_key3]; + } + for (var _i = 0, _patterns = patterns; _i < _patterns.length; _i++) { + var _patterns$_i = _patterns[_i], regex = _patterns$_i[0], extractor = _patterns$_i[1]; + var m = regex.exec(s); if (m) { return extractor(m); } } return [null, null]; } - - function simpleParse(...keys) { - return (match, cursor) => { - const ret = {}; - let i; - + function simpleParse() { + for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + keys[_key4] = arguments[_key4]; + } + return function (match, cursor) { + var ret = {}; + var i; for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInteger(match[cursor + i]); } return [ret, null, cursor + i]; }; } - - // ISO and SQL parsing - const offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; - const isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; - const isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; - const isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); - const isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`); - const isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; - const isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; - const isoOrdinalRegex = /(\d{4})-?(\d{3})/; - const extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); - const extractISOOrdinalData = simpleParse("year", "ordinal"); - const sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; // dumbed-down version of the ISO one - const sqlTimeRegex = RegExp( - `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?` - ); - const sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); - + var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; + var isoExtendedZone = "(?:" + offsetRegex.source + "?(?:\\[(" + ianaRegex.source + ")\\])?)?"; + var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; + var isoTimeRegex = RegExp("" + isoTimeBaseRegex.source + isoExtendedZone); + var isoTimeExtensionRegex = RegExp("(?:T" + isoTimeRegex.source + ")?"); + var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; + var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; + var isoOrdinalRegex = /(\d{4})-?(\d{3})/; + var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); + var extractISOOrdinalData = simpleParse("year", "ordinal"); + var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; + var sqlTimeRegex = RegExp(isoTimeBaseRegex.source + " ?(?:" + offsetRegex.source + "|(" + ianaRegex.source + "))?"); + var sqlTimeExtensionRegex = RegExp("(?: " + sqlTimeRegex.source + ")?"); function int(match, pos, fallback) { - const m = match[pos]; + var m = match[pos]; return isUndefined(m) ? fallback : parseInteger(m); } - function extractISOYmd(match, cursor) { - const item = { + var item = { year: int(match, cursor), month: int(match, cursor + 1, 1), - day: int(match, cursor + 2, 1), + day: int(match, cursor + 2, 1) }; - return [item, null, cursor + 3]; } - function extractISOTime(match, cursor) { - const item = { + var item = { hours: int(match, cursor, 0), minutes: int(match, cursor + 1, 0), seconds: int(match, cursor + 2, 0), - milliseconds: parseMillis(match[cursor + 3]), + milliseconds: parseMillis(match[cursor + 3]) }; - return [item, null, cursor + 4]; } - function extractISOOffset(match, cursor) { - const local = !match[cursor] && !match[cursor + 1], - fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), - zone = local ? null : FixedOffsetZone.instance(fullOffset); + var local = !match[cursor] && !match[cursor + 1], fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } - function extractIANAZone(match, cursor) { - const zone = match[cursor] ? IANAZone.create(match[cursor]) : null; + var zone = match[cursor] ? IANAZone.create(match[cursor]) : null; return [{}, zone, cursor + 1]; } - - // ISO time parsing - - const isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); - - // ISO duration parsing - - const isoDuration = - /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; - + var isoTimeOnly = RegExp("^T?" + isoTimeBaseRegex.source + "$"); + var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; function extractISODuration(match) { - const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = - match; - - const hasNegativePrefix = s[0] === "-"; - const negativeSeconds = secondStr && secondStr[0] === "-"; - - const maybeNegate = (num, force = false) => - num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num; - - return [ - { - years: maybeNegate(parseFloating(yearStr)), - months: maybeNegate(parseFloating(monthStr)), - weeks: maybeNegate(parseFloating(weekStr)), - days: maybeNegate(parseFloating(dayStr)), - hours: maybeNegate(parseFloating(hourStr)), - minutes: maybeNegate(parseFloating(minuteStr)), - seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), - milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds), - }, - ]; - } - - // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York - // and not just that we're in -240 *right now*. But since I don't think these are used that often - // I'm just going to ignore that - const obsOffsets = { + var s = match[0], yearStr = match[1], monthStr = match[2], weekStr = match[3], dayStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], millisecondsStr = match[8]; + var hasNegativePrefix = s[0] === "-"; + var negativeSeconds = secondStr && secondStr[0] === "-"; + var maybeNegate = function maybeNegate(num, force) { + if (force === void 0) { + force = false; + } + return num !== undefined && (force || num && hasNegativePrefix) ? -num : num; + }; + return [{ + years: maybeNegate(parseFloating(yearStr)), + months: maybeNegate(parseFloating(monthStr)), + weeks: maybeNegate(parseFloating(weekStr)), + days: maybeNegate(parseFloating(dayStr)), + hours: maybeNegate(parseFloating(hourStr)), + minutes: maybeNegate(parseFloating(minuteStr)), + seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), + milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) + }]; + } + var obsOffsets = { GMT: 0, EDT: -4 * 60, EST: -5 * 60, @@ -2780,51 +2391,26 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, - PST: -8 * 60, + PST: -8 * 60 }; - function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { - const result = { + var result = { year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), month: monthsShort.indexOf(monthStr) + 1, day: parseInteger(dayStr), hour: parseInteger(hourStr), - minute: parseInteger(minuteStr), + minute: parseInteger(minuteStr) }; - if (secondStr) result.second = parseInteger(secondStr); if (weekdayStr) { - result.weekday = - weekdayStr.length > 3 - ? weekdaysLong.indexOf(weekdayStr) + 1 - : weekdaysShort.indexOf(weekdayStr) + 1; + result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; } - return result; } - - // RFC 2822/5322 - const rfc2822 = - /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; - + var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; function extractRFC2822(match) { - const [ - , - weekdayStr, - dayStr, - monthStr, - yearStr, - hourStr, - minuteStr, - secondStr, - obsOffset, - milOffset, - offHourStr, - offMinuteStr, - ] = match, - result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - - let offset; + var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], obsOffset = match[8], milOffset = match[9], offHourStr = match[10], offMinuteStr = match[11], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + var offset; if (obsOffset) { offset = obsOffsets[obsOffset]; } else if (milOffset) { @@ -2832,272 +2418,167 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { offset = signedOffset(offHourStr, offMinuteStr); } - return [result, new FixedOffsetZone(offset)]; } - function preprocessRFC2822(s) { - // Remove comments and folding whitespace and replace multiple-spaces with a single space - return s - .replace(/\([^()]*\)|[\n\t]/g, " ") - .replace(/(\s\s+)/g, " ") - .trim(); + return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); } - - // http date - - const rfc1123 = - /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/, - rfc850 = - /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/, - ascii = - /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; - + var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/, rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/, ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; function extractRFC1123Or850(match) { - const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match, - result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } - function extractASCII(match) { - const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match, - result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + var weekdayStr = match[1], monthStr = match[2], dayStr = match[3], hourStr = match[4], minuteStr = match[5], secondStr = match[6], yearStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } - - const isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); - const isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); - const isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); - const isoTimeCombinedRegex = combineRegexes(isoTimeRegex); - - const extractISOYmdTimeAndOffset = combineExtractors( - extractISOYmd, - extractISOTime, - extractISOOffset, - extractIANAZone - ); - const extractISOWeekTimeAndOffset = combineExtractors( - extractISOWeekData, - extractISOTime, - extractISOOffset, - extractIANAZone - ); - const extractISOOrdinalDateAndTime = combineExtractors( - extractISOOrdinalData, - extractISOTime, - extractISOOffset, - extractIANAZone - ); - const extractISOTimeAndOffset = combineExtractors( - extractISOTime, - extractISOOffset, - extractIANAZone - ); - - /* - * @private - */ - + var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); + var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); + var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); + var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); + var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); + var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone); + var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone); + var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); function parseISODate(s) { - return parse( - s, - [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], - [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], - [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], - [isoTimeCombinedRegex, extractISOTimeAndOffset] - ); + return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); } - function parseRFC2822Date(s) { return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]); } - function parseHTTPDate(s) { - return parse( - s, - [rfc1123, extractRFC1123Or850], - [rfc850, extractRFC1123Or850], - [ascii, extractASCII] - ); + return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); } - function parseISODuration(s) { return parse(s, [isoDuration, extractISODuration]); } - - const extractISOTimeOnly = combineExtractors(extractISOTime); - + var extractISOTimeOnly = combineExtractors(extractISOTime); function parseISOTimeOnly(s) { return parse(s, [isoTimeOnly, extractISOTimeOnly]); } - - const sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); - const sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); - - const extractISOTimeOffsetAndIANAZone = combineExtractors( - extractISOTime, - extractISOOffset, - extractIANAZone - ); - + var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); + var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); + var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); function parseSQL(s) { - return parse( - s, - [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], - [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone] - ); - } - - const INVALID$2 = "Invalid Duration"; - - // unit conversion constants - const lowOrderMatrix = { - weeks: { - days: 7, - hours: 7 * 24, - minutes: 7 * 24 * 60, - seconds: 7 * 24 * 60 * 60, - milliseconds: 7 * 24 * 60 * 60 * 1000, - }, - days: { - hours: 24, - minutes: 24 * 60, - seconds: 24 * 60 * 60, - milliseconds: 24 * 60 * 60 * 1000, - }, - hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 }, - minutes: { seconds: 60, milliseconds: 60 * 1000 }, - seconds: { milliseconds: 1000 }, + return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); + } + var INVALID$2 = "Invalid Duration"; + var lowOrderMatrix = { + weeks: { + days: 7, + hours: 7 * 24, + minutes: 7 * 24 * 60, + seconds: 7 * 24 * 60 * 60, + milliseconds: 7 * 24 * 60 * 60 * 1000 }, - casualMatrix = { - years: { - quarters: 4, - months: 12, - weeks: 52, - days: 365, - hours: 365 * 24, - minutes: 365 * 24 * 60, - seconds: 365 * 24 * 60 * 60, - milliseconds: 365 * 24 * 60 * 60 * 1000, - }, - quarters: { - months: 3, - weeks: 13, - days: 91, - hours: 91 * 24, - minutes: 91 * 24 * 60, - seconds: 91 * 24 * 60 * 60, - milliseconds: 91 * 24 * 60 * 60 * 1000, - }, - months: { - weeks: 4, - days: 30, - hours: 30 * 24, - minutes: 30 * 24 * 60, - seconds: 30 * 24 * 60 * 60, - milliseconds: 30 * 24 * 60 * 60 * 1000, - }, - - ...lowOrderMatrix, + days: { + hours: 24, + minutes: 24 * 60, + seconds: 24 * 60 * 60, + milliseconds: 24 * 60 * 60 * 1000 }, - daysInYearAccurate = 146097.0 / 400, - daysInMonthAccurate = 146097.0 / 4800, - accurateMatrix = { - years: { - quarters: 4, - months: 12, - weeks: daysInYearAccurate / 7, - days: daysInYearAccurate, - hours: daysInYearAccurate * 24, - minutes: daysInYearAccurate * 24 * 60, - seconds: daysInYearAccurate * 24 * 60 * 60, - milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000, - }, - quarters: { - months: 3, - weeks: daysInYearAccurate / 28, - days: daysInYearAccurate / 4, - hours: (daysInYearAccurate * 24) / 4, - minutes: (daysInYearAccurate * 24 * 60) / 4, - seconds: (daysInYearAccurate * 24 * 60 * 60) / 4, - milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4, - }, - months: { - weeks: daysInMonthAccurate / 7, - days: daysInMonthAccurate, - hours: daysInMonthAccurate * 24, - minutes: daysInMonthAccurate * 24 * 60, - seconds: daysInMonthAccurate * 24 * 60 * 60, - milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000, - }, - ...lowOrderMatrix, - }; - - // units ordered by size - const orderedUnits$1 = [ - "years", - "quarters", - "months", - "weeks", - "days", - "hours", - "minutes", - "seconds", - "milliseconds", - ]; - - const reverseUnits = orderedUnits$1.slice(0).reverse(); - - // clone really means "create another instance just like this one, but with these changes" - function clone$1(dur, alts, clear = false) { - // deep merge for vals - const conf = { - values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) }, + hours: { + minutes: 60, + seconds: 60 * 60, + milliseconds: 60 * 60 * 1000 + }, + minutes: { + seconds: 60, + milliseconds: 60 * 1000 + }, + seconds: { + milliseconds: 1000 + } + }, casualMatrix = _extends({ + years: { + quarters: 4, + months: 12, + weeks: 52, + days: 365, + hours: 365 * 24, + minutes: 365 * 24 * 60, + seconds: 365 * 24 * 60 * 60, + milliseconds: 365 * 24 * 60 * 60 * 1000 + }, + quarters: { + months: 3, + weeks: 13, + days: 91, + hours: 91 * 24, + minutes: 91 * 24 * 60, + seconds: 91 * 24 * 60 * 60, + milliseconds: 91 * 24 * 60 * 60 * 1000 + }, + months: { + weeks: 4, + days: 30, + hours: 30 * 24, + minutes: 30 * 24 * 60, + seconds: 30 * 24 * 60 * 60, + milliseconds: 30 * 24 * 60 * 60 * 1000 + } + }, lowOrderMatrix), daysInYearAccurate = 146097 / 400, daysInMonthAccurate = 146097 / 4800, accurateMatrix = _extends({ + years: { + quarters: 4, + months: 12, + weeks: daysInYearAccurate / 7, + days: daysInYearAccurate, + hours: daysInYearAccurate * 24, + minutes: daysInYearAccurate * 24 * 60, + seconds: daysInYearAccurate * 24 * 60 * 60, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 + }, + quarters: { + months: 3, + weeks: daysInYearAccurate / 28, + days: daysInYearAccurate / 4, + hours: daysInYearAccurate * 24 / 4, + minutes: daysInYearAccurate * 24 * 60 / 4, + seconds: daysInYearAccurate * 24 * 60 * 60 / 4, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4 + }, + months: { + weeks: daysInMonthAccurate / 7, + days: daysInMonthAccurate, + hours: daysInMonthAccurate * 24, + minutes: daysInMonthAccurate * 24 * 60, + seconds: daysInMonthAccurate * 24 * 60 * 60, + milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 + } + }, lowOrderMatrix); + var orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"]; + var reverseUnits = orderedUnits$1.slice(0).reverse(); + function clone$1(dur, alts, clear) { + if (clear === void 0) { + clear = false; + } + var conf = { + values: clear ? alts.values : _extends({}, dur.values, alts.values || ({})), loc: dur.loc.clone(alts.loc), conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, - matrix: alts.matrix || dur.matrix, + matrix: alts.matrix || dur.matrix }; return new Duration(conf); } - function durationToMillis(matrix, vals) { - let sum = vals.milliseconds ?? 0; - for (const unit of reverseUnits.slice(1)) { + var _vals$milliseconds; + var sum = (_vals$milliseconds = vals.milliseconds) != null ? _vals$milliseconds : 0; + for (var _iterator = _createForOfIteratorHelperLoose(reverseUnits.slice(1)), _step; !(_step = _iterator()).done; ) { + var unit = _step.value; if (vals[unit]) { sum += vals[unit] * matrix[unit]["milliseconds"]; } } return sum; } - - // NB: mutates parameters function normalizeValues(matrix, vals) { - // the logic below assumes the overall value of the duration is positive - // if this is not the case, factor is used to make it so - const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; - - orderedUnits$1.reduceRight((previous, current) => { + var factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; + orderedUnits$1.reduceRight(function (previous, current) { if (!isUndefined(vals[current])) { if (previous) { - const previousVal = vals[previous] * factor; - const conv = matrix[current][previous]; - - // if (previousVal < 0): - // lower order unit is negative (e.g. { years: 2, days: -2 }) - // normalize this by reducing the higher order unit by the appropriate amount - // and increasing the lower order unit - // this can never make the higher order unit negative, because this function only operates - // on positive durations, so the amount of time represented by the lower order unit cannot - // be larger than the higher order unit - // else: - // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 }) - // in this case we attempt to convert as much as possible from the lower order unit into - // the higher order one - // - // Math.floor takes care of both of these cases, rounding away from 0 - // if previousVal < 0 it makes the absolute value larger - // if previousVal >= it makes the absolute value smaller - const rollUp = Math.floor(previousVal / conv); + var previousVal = vals[previous] * factor; + var conv = matrix[current][previous]; + var rollUp = Math.floor(previousVal / conv); vals[current] += rollUp * factor; vals[previous] -= rollUp * conv * factor; } @@ -3106,13 +2587,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return previous; } }, null); - - // try to convert any decimals into smaller units if possible - // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 } - orderedUnits$1.reduce((previous, current) => { + orderedUnits$1.reduce(function (previous, current) { if (!isUndefined(vals[current])) { if (previous) { - const fraction = vals[previous] % 1; + var fraction = vals[previous] % 1; vals[previous] -= fraction; vals[current] += fraction * matrix[previous][current]; } @@ -3122,130 +2600,50 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }, null); } - - // Remove all properties with a value of 0 from an object function removeZeroes(vals) { - const newVals = {}; - for (const [key, value] of Object.entries(vals)) { + var newVals = {}; + for (var _i = 0, _Object$entries = Object.entries(vals); _i < _Object$entries.length; _i++) { + var _Object$entries$_i = _Object$entries[_i], key = _Object$entries$_i[0], value = _Object$entries$_i[1]; if (value !== 0) { newVals[key] = value; } } return newVals; } - - /** - * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime. - * - * Here is a brief overview of commonly used methods and getters in Duration: - * - * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}. - * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors. - * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors. - * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}. - * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON} - * - * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation. - */ - class Duration { - /** - * @private - */ - constructor(config) { - const accurate = config.conversionAccuracy === "longterm" || false; - let matrix = accurate ? accurateMatrix : casualMatrix; - + var Duration = (function (_Symbol$for) { + function Duration(config) { + var accurate = config.conversionAccuracy === "longterm" || false; + var matrix = accurate ? accurateMatrix : casualMatrix; if (config.matrix) { matrix = config.matrix; } - - /** - * @access private - */ this.values = config.values; - /** - * @access private - */ this.loc = config.loc || Locale.create(); - /** - * @access private - */ this.conversionAccuracy = accurate ? "longterm" : "casual"; - /** - * @access private - */ this.invalid = config.invalid || null; - /** - * @access private - */ this.matrix = matrix; - /** - * @access private - */ this.isLuxonDuration = true; } - - /** - * Create Duration from a number of milliseconds. - * @param {number} count of milliseconds - * @param {Object} opts - options for parsing - * @param {string} [opts.locale='en-US'] - the locale to use - * @param {string} opts.numberingSystem - the numbering system to use - * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use - * @return {Duration} - */ - static fromMillis(count, opts) { - return Duration.fromObject({ milliseconds: count }, opts); - } - - /** - * Create a Duration from a JavaScript object with keys like 'years' and 'hours'. - * If this object is empty then a zero milliseconds duration is returned. - * @param {Object} obj - the object to create the DateTime from - * @param {number} obj.years - * @param {number} obj.quarters - * @param {number} obj.months - * @param {number} obj.weeks - * @param {number} obj.days - * @param {number} obj.hours - * @param {number} obj.minutes - * @param {number} obj.seconds - * @param {number} obj.milliseconds - * @param {Object} [opts=[]] - options for creating this Duration - * @param {string} [opts.locale='en-US'] - the locale to use - * @param {string} opts.numberingSystem - the numbering system to use - * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use - * @param {string} [opts.matrix=Object] - the custom conversion system to use - * @return {Duration} - */ - static fromObject(obj, opts = {}) { + Duration.fromMillis = function fromMillis(count, opts) { + return Duration.fromObject({ + milliseconds: count + }, opts); + }; + Duration.fromObject = function fromObject(obj, opts) { + if (opts === void 0) { + opts = {}; + } if (obj == null || typeof obj !== "object") { - throw new InvalidArgumentError( - `Duration.fromObject: argument expected to be an object, got ${ - obj === null ? "null" : typeof obj - }` - ); + throw new InvalidArgumentError("Duration.fromObject: argument expected to be an object, got " + (obj === null ? "null" : typeof obj)); } - return new Duration({ values: normalizeObject(obj, Duration.normalizeUnit), loc: Locale.fromObject(opts), conversionAccuracy: opts.conversionAccuracy, - matrix: opts.matrix, + matrix: opts.matrix }); - } - - /** - * Create a Duration from DurationLike. - * - * @param {Object | number | Duration} durationLike - * One of: - * - object with keys like 'years' and 'hours'. - * - number representing milliseconds - * - Duration instance - * @return {Duration} - */ - static fromDurationLike(durationLike) { + }; + Duration.fromDurationLike = function fromDurationLike(durationLike) { if (isNumber(durationLike)) { return Duration.fromMillis(durationLike); } else if (Duration.isDuration(durationLike)) { @@ -3253,85 +2651,43 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else if (typeof durationLike === "object") { return Duration.fromObject(durationLike); } else { - throw new InvalidArgumentError( - `Unknown duration argument ${durationLike} of type ${typeof durationLike}` - ); + throw new InvalidArgumentError("Unknown duration argument " + durationLike + " of type " + typeof durationLike); } - } - - /** - * Create a Duration from an ISO 8601 duration string. - * @param {string} text - text to parse - * @param {Object} opts - options for parsing - * @param {string} [opts.locale='en-US'] - the locale to use - * @param {string} opts.numberingSystem - the numbering system to use - * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use - * @param {string} [opts.matrix=Object] - the preset conversion system to use - * @see https://en.wikipedia.org/wiki/ISO_8601#Durations - * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } - * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } - * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } - * @return {Duration} - */ - static fromISO(text, opts) { - const [parsed] = parseISODuration(text); + }; + Duration.fromISO = function fromISO(text, opts) { + var _parseISODuration = parseISODuration(text), parsed = _parseISODuration[0]; if (parsed) { return Duration.fromObject(parsed, opts); } else { - return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); + return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } - } - - /** - * Create a Duration from an ISO 8601 time string. - * @param {string} text - text to parse - * @param {Object} opts - options for parsing - * @param {string} [opts.locale='en-US'] - the locale to use - * @param {string} opts.numberingSystem - the numbering system to use - * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use - * @param {string} [opts.matrix=Object] - the conversion system to use - * @see https://en.wikipedia.org/wiki/ISO_8601#Times - * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } - * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } - * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } - * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } - * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } - * @return {Duration} - */ - static fromISOTime(text, opts) { - const [parsed] = parseISOTimeOnly(text); + }; + Duration.fromISOTime = function fromISOTime(text, opts) { + var _parseISOTimeOnly = parseISOTimeOnly(text), parsed = _parseISOTimeOnly[0]; if (parsed) { return Duration.fromObject(parsed, opts); } else { - return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); + return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); + } + }; + Duration.invalid = function invalid(reason, explanation) { + if (explanation === void 0) { + explanation = null; } - } - - /** - * Create an invalid Duration. - * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent - * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information - * @return {Duration} - */ - static invalid(reason, explanation = null) { if (!reason) { throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); } - - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - + var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDurationError(invalid); } else { - return new Duration({ invalid }); + return new Duration({ + invalid: invalid + }); } - } - - /** - * @private - */ - static normalizeUnit(unit) { - const normalized = { + }; + Duration.normalizeUnit = function normalizeUnit(unit) { + var normalized = ({ year: "years", years: "years", quarter: "quarters", @@ -3349,1480 +2705,784 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; second: "seconds", seconds: "seconds", millisecond: "milliseconds", - milliseconds: "milliseconds", - }[unit ? unit.toLowerCase() : unit]; - + milliseconds: "milliseconds" + })[unit ? unit.toLowerCase() : unit]; if (!normalized) throw new InvalidUnitError(unit); - return normalized; - } - - /** - * Check if an object is a Duration. Works across context boundaries - * @param {object} o - * @return {boolean} - */ - static isDuration(o) { - return (o && o.isLuxonDuration) || false; - } - - /** - * Get the locale of a Duration, such 'en-GB' - * @type {string} - */ - get locale() { - return this.isValid ? this.loc.locale : null; - } - - /** - * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration - * - * @type {string} - */ - get numberingSystem() { - return this.isValid ? this.loc.numberingSystem : null; - } - - /** - * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: - * * `S` for milliseconds - * * `s` for seconds - * * `m` for minutes - * * `h` for hours - * * `d` for days - * * `w` for weeks - * * `M` for months - * * `y` for years - * Notes: - * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits - * * Tokens can be escaped by wrapping with single quotes. - * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting. - * @param {string} fmt - the format string - * @param {Object} opts - options - * @param {boolean} [opts.floor=true] - floor numerical values - * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" - * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" - * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" - * @return {string} - */ - toFormat(fmt, opts = {}) { - // reverse-compat since 1.2; we always round down now, never up, and we do it by default - const fmtOpts = { - ...opts, - floor: opts.round !== false && opts.floor !== false, - }; - return this.isValid - ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) - : INVALID$2; - } - - /** - * Returns a string representation of a Duration with all units included. - * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options - * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`. - * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor. - * @example - * ```js - * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 }) - * dur.toHuman() //=> '1 day, 5 hours, 6 minutes' - * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes' - * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' - * ``` - */ - toHuman(opts = {}) { + }; + Duration.isDuration = function isDuration(o) { + return o && o.isLuxonDuration || false; + }; + var _proto = Duration.prototype; + _proto.toFormat = function toFormat(fmt, opts) { + if (opts === void 0) { + opts = {}; + } + var fmtOpts = _extends({}, opts, { + floor: opts.round !== false && opts.floor !== false + }); + return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; + }; + _proto.toHuman = function toHuman(opts) { + var _this = this; + if (opts === void 0) { + opts = {}; + } if (!this.isValid) return INVALID$2; - - const l = orderedUnits$1 - .map((unit) => { - const val = this.values[unit]; - if (isUndefined(val)) { - return null; - } - return this.loc - .numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }) - .format(val); - }) - .filter((n) => n); - - return this.loc - .listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }) - .format(l); - } - - /** - * Returns a JavaScript object with this Duration's values. - * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } - * @return {Object} - */ - toObject() { + var l = orderedUnits$1.map(function (unit) { + var val = _this.values[unit]; + if (isUndefined(val)) { + return null; + } + return _this.loc.numberFormatter(_extends({ + style: "unit", + unitDisplay: "long" + }, opts, { + unit: unit.slice(0, -1) + })).format(val); + }).filter(function (n) { + return n; + }); + return this.loc.listFormatter(_extends({ + type: "conjunction", + style: opts.listStyle || "narrow" + }, opts)).format(l); + }; + _proto.toObject = function toObject() { if (!this.isValid) return {}; - return { ...this.values }; - } - - /** - * Returns an ISO 8601-compliant string representation of this Duration. - * @see https://en.wikipedia.org/wiki/ISO_8601#Durations - * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' - * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' - * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' - * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' - * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' - * @return {string} - */ - toISO() { - // we could use the formatter, but this is an easier way to get the minimum string + return _extends({}, this.values); + }; + _proto.toISO = function toISO() { if (!this.isValid) return null; - - let s = "P"; + var s = "P"; if (this.years !== 0) s += this.years + "Y"; if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M"; if (this.weeks !== 0) s += this.weeks + "W"; if (this.days !== 0) s += this.days + "D"; - if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) - s += "T"; + if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T"; if (this.hours !== 0) s += this.hours + "H"; if (this.minutes !== 0) s += this.minutes + "M"; - if (this.seconds !== 0 || this.milliseconds !== 0) - // this will handle "floating point madness" by removing extra decimal places - // https://stackoverflow.com/questions/588004/is-floating-point-math-broken - s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; + if (this.seconds !== 0 || this.milliseconds !== 0) s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; if (s === "P") s += "T0S"; return s; - } - - /** - * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. - * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. - * @see https://en.wikipedia.org/wiki/ISO_8601#Times - * @param {Object} opts - options - * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 - * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 - * @param {boolean} [opts.includePrefix=false] - include the `T` prefix - * @param {string} [opts.format='extended'] - choose between the basic and extended format - * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' - * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' - * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' - * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' - * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' - * @return {string} - */ - toISOTime(opts = {}) { + }; + _proto.toISOTime = function toISOTime(opts) { + if (opts === void 0) { + opts = {}; + } if (!this.isValid) return null; - - const millis = this.toMillis(); + var millis = this.toMillis(); if (millis < 0 || millis >= 86400000) return null; - - opts = { + opts = _extends({ suppressMilliseconds: false, suppressSeconds: false, includePrefix: false, - format: "extended", - ...opts, - includeOffset: false, - }; - - const dateTime = DateTime.fromMillis(millis, { zone: "UTC" }); + format: "extended" + }, opts, { + includeOffset: false + }); + var dateTime = DateTime.fromMillis(millis, { + zone: "UTC" + }); return dateTime.toISOTime(opts); - } - - /** - * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. - * @return {string} - */ - toJSON() { + }; + _proto.toJSON = function toJSON() { return this.toISO(); - } - - /** - * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. - * @return {string} - */ - toString() { + }; + _proto.toString = function toString() { return this.toISO(); - } - - /** - * Returns a string representation of this Duration appropriate for the REPL. - * @return {string} - */ - [Symbol.for("nodejs.util.inspect.custom")]() { + }; + _proto[_Symbol$for] = function () { if (this.isValid) { - return `Duration { values: ${JSON.stringify(this.values)} }`; + return "Duration { values: " + JSON.stringify(this.values) + " }"; } else { - return `Duration { Invalid, reason: ${this.invalidReason} }`; + return "Duration { Invalid, reason: " + this.invalidReason + " }"; } - } - - /** - * Returns an milliseconds value of this Duration. - * @return {number} - */ - toMillis() { + }; + _proto.toMillis = function toMillis() { if (!this.isValid) return NaN; - return durationToMillis(this.matrix, this.values); - } - - /** - * Returns an milliseconds value of this Duration. Alias of {@link toMillis} - * @return {number} - */ - valueOf() { + }; + _proto.valueOf = function valueOf() { return this.toMillis(); - } - - /** - * Make this Duration longer by the specified amount. Return a newly-constructed Duration. - * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() - * @return {Duration} - */ - plus(duration) { + }; + _proto.plus = function plus(duration) { if (!this.isValid) return this; - - const dur = Duration.fromDurationLike(duration), - result = {}; - - for (const k of orderedUnits$1) { + var dur = Duration.fromDurationLike(duration), result = {}; + for (var _i2 = 0, _orderedUnits = orderedUnits$1; _i2 < _orderedUnits.length; _i2++) { + var k = _orderedUnits[_i2]; if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { result[k] = dur.get(k) + this.get(k); } } - - return clone$1(this, { values: result }, true); - } - - /** - * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. - * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() - * @return {Duration} - */ - minus(duration) { + return clone$1(this, { + values: result + }, true); + }; + _proto.minus = function minus(duration) { if (!this.isValid) return this; - - const dur = Duration.fromDurationLike(duration); + var dur = Duration.fromDurationLike(duration); return this.plus(dur.negate()); - } - - /** - * Scale this Duration by the specified amount. Return a newly-constructed Duration. - * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. - * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } - * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } - * @return {Duration} - */ - mapUnits(fn) { + }; + _proto.mapUnits = function mapUnits(fn) { if (!this.isValid) return this; - const result = {}; - for (const k of Object.keys(this.values)) { + var result = {}; + for (var _i3 = 0, _Object$keys = Object.keys(this.values); _i3 < _Object$keys.length; _i3++) { + var k = _Object$keys[_i3]; result[k] = asNumber(fn(this.values[k], k)); } - return clone$1(this, { values: result }, true); - } - - /** - * Get the value of unit. - * @param {string} unit - a unit such as 'minute' or 'day' - * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 - * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 - * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 - * @return {number} - */ - get(unit) { + return clone$1(this, { + values: result + }, true); + }; + _proto.get = function get(unit) { return this[Duration.normalizeUnit(unit)]; - } - - /** - * "Set" the values of specified units. Return a newly-constructed Duration. - * @param {Object} values - a mapping of units to numbers - * @example dur.set({ years: 2017 }) - * @example dur.set({ hours: 8, minutes: 30 }) - * @return {Duration} - */ - set(values) { + }; + _proto.set = function set(values) { if (!this.isValid) return this; - - const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) }; - return clone$1(this, { values: mixed }); - } - - /** - * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. - * @example dur.reconfigure({ locale: 'en-GB' }) - * @return {Duration} - */ - reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { - const loc = this.loc.clone({ locale, numberingSystem }); - const opts = { loc, matrix, conversionAccuracy }; + var mixed = _extends({}, this.values, normalizeObject(values, Duration.normalizeUnit)); + return clone$1(this, { + values: mixed + }); + }; + _proto.reconfigure = function reconfigure(_temp) { + var _ref = _temp === void 0 ? {} : _temp, locale = _ref.locale, numberingSystem = _ref.numberingSystem, conversionAccuracy = _ref.conversionAccuracy, matrix = _ref.matrix; + var loc = this.loc.clone({ + locale: locale, + numberingSystem: numberingSystem + }); + var opts = { + loc: loc, + matrix: matrix, + conversionAccuracy: conversionAccuracy + }; return clone$1(this, opts); - } - - /** - * Return the length of the duration in the specified unit. - * @param {string} unit - a unit such as 'minutes' or 'days' - * @example Duration.fromObject({years: 1}).as('days') //=> 365 - * @example Duration.fromObject({years: 1}).as('months') //=> 12 - * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 - * @return {number} - */ - as(unit) { + }; + _proto.as = function as(unit) { return this.isValid ? this.shiftTo(unit).get(unit) : NaN; - } - - /** - * Reduce this Duration to its canonical representation in its current units. - * Assuming the overall value of the Duration is positive, this means: - * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example) - * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise - * the overall value would be negative, see third example) - * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example) - * - * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`. - * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } - * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 } - * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } - * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 } - * @return {Duration} - */ - normalize() { + }; + _proto.normalize = function normalize() { if (!this.isValid) return this; - const vals = this.toObject(); + var vals = this.toObject(); normalizeValues(this.matrix, vals); - return clone$1(this, { values: vals }, true); - } - - /** - * Rescale units to its largest representation - * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 } - * @return {Duration} - */ - rescale() { + return clone$1(this, { + values: vals + }, true); + }; + _proto.rescale = function rescale() { if (!this.isValid) return this; - const vals = removeZeroes(this.normalize().shiftToAll().toObject()); - return clone$1(this, { values: vals }, true); - } - - /** - * Convert this Duration into its representation in a different set of units. - * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } - * @return {Duration} - */ - shiftTo(...units) { + var vals = removeZeroes(this.normalize().shiftToAll().toObject()); + return clone$1(this, { + values: vals + }, true); + }; + _proto.shiftTo = function shiftTo() { + for (var _len = arguments.length, units = new Array(_len), _key = 0; _key < _len; _key++) { + units[_key] = arguments[_key]; + } if (!this.isValid) return this; - if (units.length === 0) { return this; } - - units = units.map((u) => Duration.normalizeUnit(u)); - - const built = {}, - accumulated = {}, - vals = this.toObject(); - let lastUnit; - - for (const k of orderedUnits$1) { + units = units.map(function (u) { + return Duration.normalizeUnit(u); + }); + var built = {}, accumulated = {}, vals = this.toObject(); + var lastUnit; + for (var _i4 = 0, _orderedUnits2 = orderedUnits$1; _i4 < _orderedUnits2.length; _i4++) { + var k = _orderedUnits2[_i4]; if (units.indexOf(k) >= 0) { lastUnit = k; - - let own = 0; - - // anything we haven't boiled down yet should get boiled to this unit - for (const ak in accumulated) { + var own = 0; + for (var ak in accumulated) { own += this.matrix[ak][k] * accumulated[ak]; accumulated[ak] = 0; } - - // plus anything that's already in this unit if (isNumber(vals[k])) { own += vals[k]; } - - // only keep the integer part for now in the hopes of putting any decimal part - // into a smaller unit later - const i = Math.trunc(own); + var i = Math.trunc(own); built[k] = i; accumulated[k] = (own * 1000 - i * 1000) / 1000; - - // otherwise, keep it in the wings to boil it later } else if (isNumber(vals[k])) { accumulated[k] = vals[k]; } } - - // anything leftover becomes the decimal for the last unit - // lastUnit must be defined since units is not empty - for (const key in accumulated) { + for (var key in accumulated) { if (accumulated[key] !== 0) { - built[lastUnit] += - key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; + built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } - normalizeValues(this.matrix, built); - return clone$1(this, { values: built }, true); - } - - /** - * Shift this Duration to all available units. - * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds") - * @return {Duration} - */ - shiftToAll() { + return clone$1(this, { + values: built + }, true); + }; + _proto.shiftToAll = function shiftToAll() { if (!this.isValid) return this; - return this.shiftTo( - "years", - "months", - "weeks", - "days", - "hours", - "minutes", - "seconds", - "milliseconds" - ); - } - - /** - * Return the negative of this Duration. - * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } - * @return {Duration} - */ - negate() { + return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"); + }; + _proto.negate = function negate() { if (!this.isValid) return this; - const negated = {}; - for (const k of Object.keys(this.values)) { + var negated = {}; + for (var _i5 = 0, _Object$keys2 = Object.keys(this.values); _i5 < _Object$keys2.length; _i5++) { + var k = _Object$keys2[_i5]; negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; } - return clone$1(this, { values: negated }, true); - } - - /** - * Get the years. - * @type {number} - */ - get years() { - return this.isValid ? this.values.years || 0 : NaN; - } - - /** - * Get the quarters. - * @type {number} - */ - get quarters() { - return this.isValid ? this.values.quarters || 0 : NaN; - } - - /** - * Get the months. - * @type {number} - */ - get months() { - return this.isValid ? this.values.months || 0 : NaN; - } - - /** - * Get the weeks - * @type {number} - */ - get weeks() { - return this.isValid ? this.values.weeks || 0 : NaN; - } - - /** - * Get the days. - * @type {number} - */ - get days() { - return this.isValid ? this.values.days || 0 : NaN; - } - - /** - * Get the hours. - * @type {number} - */ - get hours() { - return this.isValid ? this.values.hours || 0 : NaN; - } - - /** - * Get the minutes. - * @type {number} - */ - get minutes() { - return this.isValid ? this.values.minutes || 0 : NaN; - } - - /** - * Get the seconds. - * @return {number} - */ - get seconds() { - return this.isValid ? this.values.seconds || 0 : NaN; - } - - /** - * Get the milliseconds. - * @return {number} - */ - get milliseconds() { - return this.isValid ? this.values.milliseconds || 0 : NaN; - } - - /** - * Returns whether the Duration is invalid. Invalid durations are returned by diff operations - * on invalid DateTimes or Intervals. - * @return {boolean} - */ - get isValid() { - return this.invalid === null; - } - - /** - * Returns an error code if this Duration became invalid, or null if the Duration is valid - * @return {string} - */ - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - - /** - * Returns an explanation of why this Duration became invalid, or null if the Duration is valid - * @type {string} - */ - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - - /** - * Equality check - * Two Durations are equal iff they have the same units and the same values for each unit. - * @param {Duration} other - * @return {boolean} - */ - equals(other) { + return clone$1(this, { + values: negated + }, true); + }; + _proto.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } - if (!this.loc.equals(other.loc)) { return false; } - function eq(v1, v2) { - // Consider 0 and undefined as equal if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0; return v1 === v2; } - - for (const u of orderedUnits$1) { + for (var _i6 = 0, _orderedUnits3 = orderedUnits$1; _i6 < _orderedUnits3.length; _i6++) { + var u = _orderedUnits3[_i6]; if (!eq(this.values[u], other.values[u])) { return false; } } return true; - } - } - - const INVALID$1 = "Invalid Interval"; - - // checks if the start is equal to or before the end + }; + _createClass(Duration, [{ + key: "locale", + get: function get() { + return this.isValid ? this.loc.locale : null; + } + }, { + key: "numberingSystem", + get: function get() { + return this.isValid ? this.loc.numberingSystem : null; + } + }, { + key: "years", + get: function get() { + return this.isValid ? this.values.years || 0 : NaN; + } + }, { + key: "quarters", + get: function get() { + return this.isValid ? this.values.quarters || 0 : NaN; + } + }, { + key: "months", + get: function get() { + return this.isValid ? this.values.months || 0 : NaN; + } + }, { + key: "weeks", + get: function get() { + return this.isValid ? this.values.weeks || 0 : NaN; + } + }, { + key: "days", + get: function get() { + return this.isValid ? this.values.days || 0 : NaN; + } + }, { + key: "hours", + get: function get() { + return this.isValid ? this.values.hours || 0 : NaN; + } + }, { + key: "minutes", + get: function get() { + return this.isValid ? this.values.minutes || 0 : NaN; + } + }, { + key: "seconds", + get: function get() { + return this.isValid ? this.values.seconds || 0 : NaN; + } + }, { + key: "milliseconds", + get: function get() { + return this.isValid ? this.values.milliseconds || 0 : NaN; + } + }, { + key: "isValid", + get: function get() { + return this.invalid === null; + } + }, { + key: "invalidReason", + get: function get() { + return this.invalid ? this.invalid.reason : null; + } + }, { + key: "invalidExplanation", + get: function get() { + return this.invalid ? this.invalid.explanation : null; + } + }]); + return Duration; + })(Symbol.for("nodejs.util.inspect.custom")); + var INVALID$1 = "Invalid Interval"; function validateStartEnd(start, end) { if (!start || !start.isValid) { return Interval.invalid("missing or invalid start"); } else if (!end || !end.isValid) { return Interval.invalid("missing or invalid end"); } else if (end < start) { - return Interval.invalid( - "end before start", - `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}` - ); + return Interval.invalid("end before start", "The end of an interval must be after its start, but you had start=" + start.toISO() + " and end=" + end.toISO()); } else { return null; } } - - /** - * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them. - * - * Here is a brief overview of the most commonly used methods and getters in Interval: - * - * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}. - * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end. - * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}. - * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}. - * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs} - * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}. - */ - class Interval { - /** - * @private - */ - constructor(config) { - /** - * @access private - */ + var Interval = (function (_Symbol$for) { + function Interval(config) { this.s = config.start; - /** - * @access private - */ this.e = config.end; - /** - * @access private - */ this.invalid = config.invalid || null; - /** - * @access private - */ this.isLuxonInterval = true; } - - /** - * Create an invalid Interval. - * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent - * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information - * @return {Interval} - */ - static invalid(reason, explanation = null) { + Interval.invalid = function invalid(reason, explanation) { + if (explanation === void 0) { + explanation = null; + } if (!reason) { throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); } - - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - + var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidIntervalError(invalid); } else { - return new Interval({ invalid }); + return new Interval({ + invalid: invalid + }); } - } - - /** - * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. - * @param {DateTime|Date|Object} start - * @param {DateTime|Date|Object} end - * @return {Interval} - */ - static fromDateTimes(start, end) { - const builtStart = friendlyDateTime(start), - builtEnd = friendlyDateTime(end); - - const validateError = validateStartEnd(builtStart, builtEnd); - + }; + Interval.fromDateTimes = function fromDateTimes(start, end) { + var builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); + var validateError = validateStartEnd(builtStart, builtEnd); if (validateError == null) { return new Interval({ start: builtStart, - end: builtEnd, + end: builtEnd }); } else { return validateError; } - } - - /** - * Create an Interval from a start DateTime and a Duration to extend to. - * @param {DateTime|Date|Object} start - * @param {Duration|Object|number} duration - the length of the Interval. - * @return {Interval} - */ - static after(start, duration) { - const dur = Duration.fromDurationLike(duration), - dt = friendlyDateTime(start); + }; + Interval.after = function after(start, duration) { + var dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start); return Interval.fromDateTimes(dt, dt.plus(dur)); - } - - /** - * Create an Interval from an end DateTime and a Duration to extend backwards to. - * @param {DateTime|Date|Object} end - * @param {Duration|Object|number} duration - the length of the Interval. - * @return {Interval} - */ - static before(end, duration) { - const dur = Duration.fromDurationLike(duration), - dt = friendlyDateTime(end); + }; + Interval.before = function before(end, duration) { + var dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end); return Interval.fromDateTimes(dt.minus(dur), dt); - } - - /** - * Create an Interval from an ISO 8601 string. - * Accepts `/`, `/`, and `/` formats. - * @param {string} text - the ISO string to parse - * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO} - * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals - * @return {Interval} - */ - static fromISO(text, opts) { - const [s, e] = (text || "").split("/", 2); + }; + Interval.fromISO = function fromISO(text, opts) { + var _split = (text || "").split("/", 2), s = _split[0], e = _split[1]; if (s && e) { - let start, startIsValid; + var start, startIsValid; try { start = DateTime.fromISO(s, opts); startIsValid = start.isValid; } catch (e) { startIsValid = false; } - - let end, endIsValid; + var end, endIsValid; try { end = DateTime.fromISO(e, opts); endIsValid = end.isValid; } catch (e) { endIsValid = false; } - if (startIsValid && endIsValid) { return Interval.fromDateTimes(start, end); } - if (startIsValid) { - const dur = Duration.fromISO(e, opts); + var dur = Duration.fromISO(e, opts); if (dur.isValid) { return Interval.after(start, dur); } } else if (endIsValid) { - const dur = Duration.fromISO(s, opts); - if (dur.isValid) { - return Interval.before(end, dur); + var _dur = Duration.fromISO(s, opts); + if (_dur.isValid) { + return Interval.before(end, _dur); } } } - return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); - } - - /** - * Check if an object is an Interval. Works across context boundaries - * @param {object} o - * @return {boolean} - */ - static isInterval(o) { - return (o && o.isLuxonInterval) || false; - } - - /** - * Returns the start of the Interval - * @type {DateTime} - */ - get start() { - return this.isValid ? this.s : null; - } - - /** - * Returns the end of the Interval - * @type {DateTime} - */ - get end() { - return this.isValid ? this.e : null; - } - - /** - * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'. - * @type {boolean} - */ - get isValid() { - return this.invalidReason === null; - } - - /** - * Returns an error code if this Interval is invalid, or null if the Interval is valid - * @type {string} - */ - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - - /** - * Returns an explanation of why this Interval became invalid, or null if the Interval is valid - * @type {string} - */ - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - - /** - * Returns the length of the Interval in the specified unit. - * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. - * @return {number} - */ - length(unit = "milliseconds") { - return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; - } - - /** - * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. - * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' - * asks 'what dates are included in this interval?', not 'how many days long is this interval?' - * @param {string} [unit='milliseconds'] - the unit of time to count. - * @param {Object} opts - options - * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime - * @return {number} - */ - count(unit = "milliseconds", opts) { + return Interval.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); + }; + Interval.isInterval = function isInterval(o) { + return o && o.isLuxonInterval || false; + }; + var _proto = Interval.prototype; + _proto.length = function length(unit) { + if (unit === void 0) { + unit = "milliseconds"; + } + return this.isValid ? this.toDuration.apply(this, [unit]).get(unit) : NaN; + }; + _proto.count = function count(unit, opts) { + if (unit === void 0) { + unit = "milliseconds"; + } if (!this.isValid) return NaN; - const start = this.start.startOf(unit, opts); - let end; - if (opts?.useLocaleWeeks) { - end = this.end.reconfigure({ locale: start.locale }); + var start = this.start.startOf(unit, opts); + var end; + if (opts != null && opts.useLocaleWeeks) { + end = this.end.reconfigure({ + locale: start.locale + }); } else { end = this.end; } end = end.startOf(unit, opts); return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf()); - } - - /** - * Returns whether this Interval's start and end are both in the same unit of time - * @param {string} unit - the unit of time to check sameness on - * @return {boolean} - */ - hasSame(unit) { + }; + _proto.hasSame = function hasSame(unit) { return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; - } - - /** - * Return whether this Interval has the same start and end DateTimes. - * @return {boolean} - */ - isEmpty() { + }; + _proto.isEmpty = function isEmpty() { return this.s.valueOf() === this.e.valueOf(); - } - - /** - * Return whether this Interval's start is after the specified DateTime. - * @param {DateTime} dateTime - * @return {boolean} - */ - isAfter(dateTime) { + }; + _proto.isAfter = function isAfter(dateTime) { if (!this.isValid) return false; return this.s > dateTime; - } - - /** - * Return whether this Interval's end is before the specified DateTime. - * @param {DateTime} dateTime - * @return {boolean} - */ - isBefore(dateTime) { + }; + _proto.isBefore = function isBefore(dateTime) { if (!this.isValid) return false; return this.e <= dateTime; - } - - /** - * Return whether this Interval contains the specified DateTime. - * @param {DateTime} dateTime - * @return {boolean} - */ - contains(dateTime) { + }; + _proto.contains = function contains(dateTime) { if (!this.isValid) return false; return this.s <= dateTime && this.e > dateTime; - } - - /** - * "Sets" the start and/or end dates. Returns a newly-constructed Interval. - * @param {Object} values - the values to set - * @param {DateTime} values.start - the starting DateTime - * @param {DateTime} values.end - the ending DateTime - * @return {Interval} - */ - set({ start, end } = {}) { + }; + _proto.set = function set(_temp) { + var _ref = _temp === void 0 ? {} : _temp, start = _ref.start, end = _ref.end; if (!this.isValid) return this; return Interval.fromDateTimes(start || this.s, end || this.e); - } - - /** - * Split this Interval at each of the specified DateTimes - * @param {...DateTime} dateTimes - the unit of time to count. - * @return {Array} - */ - splitAt(...dateTimes) { + }; + _proto.splitAt = function splitAt() { + var _this = this; if (!this.isValid) return []; - const sorted = dateTimes - .map(friendlyDateTime) - .filter((d) => this.contains(d)) - .sort((a, b) => a.toMillis() - b.toMillis()), - results = []; - let { s } = this, - i = 0; - + for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { + dateTimes[_key] = arguments[_key]; + } + var sorted = dateTimes.map(friendlyDateTime).filter(function (d) { + return _this.contains(d); + }).sort(function (a, b) { + return a.toMillis() - b.toMillis(); + }), results = []; + var s = this.s, i = 0; while (s < this.e) { - const added = sorted[i] || this.e, - next = +added > +this.e ? this.e : added; + var added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; i += 1; } - return results; - } - - /** - * Split this Interval into smaller Intervals, each of the specified length. - * Left over time is grouped into a smaller interval - * @param {Duration|Object|number} duration - The length of each resulting interval. - * @return {Array} - */ - splitBy(duration) { - const dur = Duration.fromDurationLike(duration); - + }; + _proto.splitBy = function splitBy(duration) { + var dur = Duration.fromDurationLike(duration); if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { return []; } - - let { s } = this, - idx = 1, - next; - - const results = []; + var s = this.s, idx = 1, next; + var results = []; while (s < this.e) { - const added = this.start.plus(dur.mapUnits((x) => x * idx)); + var added = this.start.plus(dur.mapUnits(function (x) { + return x * idx; + })); next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; idx += 1; } - return results; - } - - /** - * Split this Interval into the specified number of smaller intervals. - * @param {number} numberOfParts - The number of Intervals to divide the Interval into. - * @return {Array} - */ - divideEqually(numberOfParts) { + }; + _proto.divideEqually = function divideEqually(numberOfParts) { if (!this.isValid) return []; return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); - } - - /** - * Return whether this Interval overlaps with the specified Interval - * @param {Interval} other - * @return {boolean} - */ - overlaps(other) { + }; + _proto.overlaps = function overlaps(other) { return this.e > other.s && this.s < other.e; - } - - /** - * Return whether this Interval's end is adjacent to the specified Interval's start. - * @param {Interval} other - * @return {boolean} - */ - abutsStart(other) { + }; + _proto.abutsStart = function abutsStart(other) { if (!this.isValid) return false; return +this.e === +other.s; - } - - /** - * Return whether this Interval's start is adjacent to the specified Interval's end. - * @param {Interval} other - * @return {boolean} - */ - abutsEnd(other) { + }; + _proto.abutsEnd = function abutsEnd(other) { if (!this.isValid) return false; return +other.e === +this.s; - } - - /** - * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise. - * @param {Interval} other - * @return {boolean} - */ - engulfs(other) { + }; + _proto.engulfs = function engulfs(other) { if (!this.isValid) return false; return this.s <= other.s && this.e >= other.e; - } - - /** - * Return whether this Interval has the same start and end as the specified Interval. - * @param {Interval} other - * @return {boolean} - */ - equals(other) { + }; + _proto.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } - return this.s.equals(other.s) && this.e.equals(other.e); - } - - /** - * Return an Interval representing the intersection of this Interval and the specified Interval. - * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. - * Returns null if the intersection is empty, meaning, the intervals don't intersect. - * @param {Interval} other - * @return {Interval} - */ - intersection(other) { + }; + _proto.intersection = function intersection(other) { if (!this.isValid) return this; - const s = this.s > other.s ? this.s : other.s, - e = this.e < other.e ? this.e : other.e; - + var s = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; if (s >= e) { return null; } else { return Interval.fromDateTimes(s, e); } - } - - /** - * Return an Interval representing the union of this Interval and the specified Interval. - * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. - * @param {Interval} other - * @return {Interval} - */ - union(other) { + }; + _proto.union = function union(other) { if (!this.isValid) return this; - const s = this.s < other.s ? this.s : other.s, - e = this.e > other.e ? this.e : other.e; + var s = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s, e); - } - - /** - * Merge an array of Intervals into a equivalent minimal set of Intervals. - * Combines overlapping and adjacent Intervals. - * @param {Array} intervals - * @return {Array} - */ - static merge(intervals) { - const [found, final] = intervals - .sort((a, b) => a.s - b.s) - .reduce( - ([sofar, current], item) => { - if (!current) { - return [sofar, item]; - } else if (current.overlaps(item) || current.abutsStart(item)) { - return [sofar, current.union(item)]; - } else { - return [sofar.concat([current]), item]; - } - }, - [[], null] - ); + }; + Interval.merge = function merge(intervals) { + var _intervals$sort$reduc = intervals.sort(function (a, b) { + return a.s - b.s; + }).reduce(function (_ref2, item) { + var sofar = _ref2[0], current = _ref2[1]; + if (!current) { + return [sofar, item]; + } else if (current.overlaps(item) || current.abutsStart(item)) { + return [sofar, current.union(item)]; + } else { + return [sofar.concat([current]), item]; + } + }, [[], null]), found = _intervals$sort$reduc[0], final = _intervals$sort$reduc[1]; if (final) { found.push(final); } return found; - } - - /** - * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. - * @param {Array} intervals - * @return {Array} - */ - static xor(intervals) { - let start = null, - currentCount = 0; - const results = [], - ends = intervals.map((i) => [ - { time: i.s, type: "s" }, - { time: i.e, type: "e" }, - ]), - flattened = Array.prototype.concat(...ends), - arr = flattened.sort((a, b) => a.time - b.time); - - for (const i of arr) { + }; + Interval.xor = function xor(intervals) { + var _Array$prototype; + var start = null, currentCount = 0; + var results = [], ends = intervals.map(function (i) { + return [{ + time: i.s, + type: "s" + }, { + time: i.e, + type: "e" + }]; + }), flattened = (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, ends), arr = flattened.sort(function (a, b) { + return a.time - b.time; + }); + for (var _iterator = _createForOfIteratorHelperLoose(arr), _step; !(_step = _iterator()).done; ) { + var i = _step.value; currentCount += i.type === "s" ? 1 : -1; - if (currentCount === 1) { start = i.time; } else { if (start && +start !== +i.time) { results.push(Interval.fromDateTimes(start, i.time)); } - start = null; } } - return Interval.merge(results); - } - - /** - * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. - * @param {...Interval} intervals - * @return {Array} - */ - difference(...intervals) { - return Interval.xor([this].concat(intervals)) - .map((i) => this.intersection(i)) - .filter((i) => i && !i.isEmpty()); - } - - /** - * Returns a string representation of this Interval appropriate for debugging. - * @return {string} - */ - toString() { + }; + _proto.difference = function difference() { + var _this2 = this; + for (var _len2 = arguments.length, intervals = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + intervals[_key2] = arguments[_key2]; + } + return Interval.xor([this].concat(intervals)).map(function (i) { + return _this2.intersection(i); + }).filter(function (i) { + return i && !i.isEmpty(); + }); + }; + _proto.toString = function toString() { if (!this.isValid) return INVALID$1; - return `[${this.s.toISO()} – ${this.e.toISO()})`; - } - - /** - * Returns a string representation of this Interval appropriate for the REPL. - * @return {string} - */ - [Symbol.for("nodejs.util.inspect.custom")]() { + return "[" + this.s.toISO() + " – " + this.e.toISO() + ")"; + }; + _proto[_Symbol$for] = function () { if (this.isValid) { - return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`; + return "Interval { start: " + this.s.toISO() + ", end: " + this.e.toISO() + " }"; } else { - return `Interval { Invalid, reason: ${this.invalidReason} }`; + return "Interval { Invalid, reason: " + this.invalidReason + " }"; } - } - - /** - * Returns a localized string representing this Interval. Accepts the same options as the - * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as - * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method - * is browser-specific, but in general it will return an appropriate representation of the - * Interval in the assigned locale. Defaults to the system's locale if no locale has been - * specified. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat - * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or - * Intl.DateTimeFormat constructor options. - * @param {Object} opts - Options to override the configuration of the start DateTime. - * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022 - * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022 - * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022 - * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM - * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p - * @return {string} - */ - toLocaleString(formatOpts = DATE_SHORT, opts = {}) { - return this.isValid - ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) - : INVALID$1; - } - - /** - * Returns an ISO 8601-compliant string representation of this Interval. - * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals - * @param {Object} opts - The same options as {@link DateTime#toISO} - * @return {string} - */ - toISO(opts) { + }; + _proto.toLocaleString = function toLocaleString(formatOpts, opts) { + if (formatOpts === void 0) { + formatOpts = DATE_SHORT; + } + if (opts === void 0) { + opts = {}; + } + return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1; + }; + _proto.toISO = function toISO(opts) { if (!this.isValid) return INVALID$1; - return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; - } - - /** - * Returns an ISO 8601-compliant string representation of date of this Interval. - * The time components are ignored. - * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals - * @return {string} - */ - toISODate() { + return this.s.toISO(opts) + "/" + this.e.toISO(opts); + }; + _proto.toISODate = function toISODate() { if (!this.isValid) return INVALID$1; - return `${this.s.toISODate()}/${this.e.toISODate()}`; - } - - /** - * Returns an ISO 8601-compliant string representation of time of this Interval. - * The date components are ignored. - * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals - * @param {Object} opts - The same options as {@link DateTime#toISO} - * @return {string} - */ - toISOTime(opts) { + return this.s.toISODate() + "/" + this.e.toISODate(); + }; + _proto.toISOTime = function toISOTime(opts) { if (!this.isValid) return INVALID$1; - return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; - } - - /** - * Returns a string representation of this Interval formatted according to the specified format - * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible - * formatting tool. - * @param {string} dateFormat - The format string. This string formats the start and end time. - * See {@link DateTime#toFormat} for details. - * @param {Object} opts - Options. - * @param {string} [opts.separator = ' – '] - A separator to place between the start and end - * representations. - * @return {string} - */ - toFormat(dateFormat, { separator = " – " } = {}) { + return this.s.toISOTime(opts) + "/" + this.e.toISOTime(opts); + }; + _proto.toFormat = function toFormat(dateFormat, _temp2) { + var _ref3 = _temp2 === void 0 ? {} : _temp2, _ref3$separator = _ref3.separator, separator = _ref3$separator === void 0 ? " – " : _ref3$separator; if (!this.isValid) return INVALID$1; - return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; - } - - /** - * Return a Duration representing the time spanned by this interval. - * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. - * @param {Object} opts - options that affect the creation of the Duration - * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use - * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } - * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } - * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } - * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } - * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } - * @return {Duration} - */ - toDuration(unit, opts) { + return "" + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat); + }; + _proto.toDuration = function toDuration(unit, opts) { if (!this.isValid) { return Duration.invalid(this.invalidReason); } return this.e.diff(this.s, unit, opts); - } - - /** - * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes - * @param {function} mapFn - * @return {Interval} - * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) - * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) - */ - mapEndpoints(mapFn) { + }; + _proto.mapEndpoints = function mapEndpoints(mapFn) { return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); - } - } - - /** - * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. - */ - class Info { - /** - * Return whether the specified zone contains a DST. - * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. - * @return {boolean} - */ - static hasDST(zone = Settings.defaultZone) { - const proto = DateTime.now().setZone(zone).set({ month: 12 }); - - return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; - } - - /** - * Return whether the specified zone is a valid IANA specifier. - * @param {string} zone - Zone to check - * @return {boolean} - */ - static isValidIANAZone(zone) { + }; + _createClass(Interval, [{ + key: "start", + get: function get() { + return this.isValid ? this.s : null; + } + }, { + key: "end", + get: function get() { + return this.isValid ? this.e : null; + } + }, { + key: "isValid", + get: function get() { + return this.invalidReason === null; + } + }, { + key: "invalidReason", + get: function get() { + return this.invalid ? this.invalid.reason : null; + } + }, { + key: "invalidExplanation", + get: function get() { + return this.invalid ? this.invalid.explanation : null; + } + }]); + return Interval; + })(Symbol.for("nodejs.util.inspect.custom")); + var Info = (function () { + function Info() {} + Info.hasDST = function hasDST(zone) { + if (zone === void 0) { + zone = Settings.defaultZone; + } + var proto = DateTime.now().setZone(zone).set({ + month: 12 + }); + return !zone.isUniversal && proto.offset !== proto.set({ + month: 6 + }).offset; + }; + Info.isValidIANAZone = function isValidIANAZone(zone) { return IANAZone.isValidZone(zone); - } - - /** - * Converts the input into a {@link Zone} instance. - * - * * If `input` is already a Zone instance, it is returned unchanged. - * * If `input` is a string containing a valid time zone name, a Zone instance - * with that name is returned. - * * If `input` is a string that doesn't refer to a known time zone, a Zone - * instance with {@link Zone#isValid} == false is returned. - * * If `input is a number, a Zone instance with the specified fixed offset - * in minutes is returned. - * * If `input` is `null` or `undefined`, the default zone is returned. - * @param {string|Zone|number} [input] - the value to be converted - * @return {Zone} - */ - static normalizeZone(input) { + }; + Info.normalizeZone = function normalizeZone$1(input) { return normalizeZone(input, Settings.defaultZone); - } - - /** - * Get the weekday on which the week starts according to the given locale. - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @param {string} [opts.locObj=null] - an existing locale object to use - * @returns {number} the start of the week, 1 for Monday through 7 for Sunday - */ - static getStartOfWeek({ locale = null, locObj = null } = {}) { + }; + Info.getStartOfWeek = function getStartOfWeek(_temp) { + var _ref = _temp === void 0 ? {} : _temp, _ref$locale = _ref.locale, locale = _ref$locale === void 0 ? null : _ref$locale, _ref$locObj = _ref.locObj, locObj = _ref$locObj === void 0 ? null : _ref$locObj; return (locObj || Locale.create(locale)).getStartOfWeek(); - } - - /** - * Get the minimum number of days necessary in a week before it is considered part of the next year according - * to the given locale. - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @param {string} [opts.locObj=null] - an existing locale object to use - * @returns {number} - */ - static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) { + }; + Info.getMinimumDaysInFirstWeek = function getMinimumDaysInFirstWeek(_temp2) { + var _ref2 = _temp2 === void 0 ? {} : _temp2, _ref2$locale = _ref2.locale, locale = _ref2$locale === void 0 ? null : _ref2$locale, _ref2$locObj = _ref2.locObj, locObj = _ref2$locObj === void 0 ? null : _ref2$locObj; return (locObj || Locale.create(locale)).getMinDaysInFirstWeek(); - } - - /** - * Get the weekdays, which are considered the weekend according to the given locale - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @param {string} [opts.locObj=null] - an existing locale object to use - * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday - */ - static getWeekendWeekdays({ locale = null, locObj = null } = {}) { - // copy the array, because we cache it internally + }; + Info.getWeekendWeekdays = function getWeekendWeekdays(_temp3) { + var _ref3 = _temp3 === void 0 ? {} : _temp3, _ref3$locale = _ref3.locale, locale = _ref3$locale === void 0 ? null : _ref3$locale, _ref3$locObj = _ref3.locObj, locObj = _ref3$locObj === void 0 ? null : _ref3$locObj; return (locObj || Locale.create(locale)).getWeekendDays().slice(); - } - - /** - * Return an array of standalone month names. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat - * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @param {string} [opts.numberingSystem=null] - the numbering system - * @param {string} [opts.locObj=null] - an existing locale object to use - * @param {string} [opts.outputCalendar='gregory'] - the calendar - * @example Info.months()[0] //=> 'January' - * @example Info.months('short')[0] //=> 'Jan' - * @example Info.months('numeric')[0] //=> '1' - * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' - * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' - * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' - * @return {Array} - */ - static months( - length = "long", - { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {} - ) { + }; + Info.months = function months(length, _temp4) { + if (length === void 0) { + length = "long"; + } + var _ref4 = _temp4 === void 0 ? {} : _temp4, _ref4$locale = _ref4.locale, locale = _ref4$locale === void 0 ? null : _ref4$locale, _ref4$numberingSystem = _ref4.numberingSystem, numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem, _ref4$locObj = _ref4.locObj, locObj = _ref4$locObj === void 0 ? null : _ref4$locObj, _ref4$outputCalendar = _ref4.outputCalendar, outputCalendar = _ref4$outputCalendar === void 0 ? "gregory" : _ref4$outputCalendar; return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); - } - - /** - * Return an array of format month names. - * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that - * changes the string. - * See {@link Info#months} - * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @param {string} [opts.numberingSystem=null] - the numbering system - * @param {string} [opts.locObj=null] - an existing locale object to use - * @param {string} [opts.outputCalendar='gregory'] - the calendar - * @return {Array} - */ - static monthsFormat( - length = "long", - { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {} - ) { + }; + Info.monthsFormat = function monthsFormat(length, _temp5) { + if (length === void 0) { + length = "long"; + } + var _ref5 = _temp5 === void 0 ? {} : _temp5, _ref5$locale = _ref5.locale, locale = _ref5$locale === void 0 ? null : _ref5$locale, _ref5$numberingSystem = _ref5.numberingSystem, numberingSystem = _ref5$numberingSystem === void 0 ? null : _ref5$numberingSystem, _ref5$locObj = _ref5.locObj, locObj = _ref5$locObj === void 0 ? null : _ref5$locObj, _ref5$outputCalendar = _ref5.outputCalendar, outputCalendar = _ref5$outputCalendar === void 0 ? "gregory" : _ref5$outputCalendar; return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); - } - - /** - * Return an array of standalone week names. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat - * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @param {string} [opts.numberingSystem=null] - the numbering system - * @param {string} [opts.locObj=null] - an existing locale object to use - * @example Info.weekdays()[0] //=> 'Monday' - * @example Info.weekdays('short')[0] //=> 'Mon' - * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' - * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' - * @return {Array} - */ - static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { + }; + Info.weekdays = function weekdays(length, _temp6) { + if (length === void 0) { + length = "long"; + } + var _ref6 = _temp6 === void 0 ? {} : _temp6, _ref6$locale = _ref6.locale, locale = _ref6$locale === void 0 ? null : _ref6$locale, _ref6$numberingSystem = _ref6.numberingSystem, numberingSystem = _ref6$numberingSystem === void 0 ? null : _ref6$numberingSystem, _ref6$locObj = _ref6.locObj, locObj = _ref6$locObj === void 0 ? null : _ref6$locObj; return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); - } - - /** - * Return an array of format week names. - * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that - * changes the string. - * See {@link Info#weekdays} - * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". - * @param {Object} opts - options - * @param {string} [opts.locale=null] - the locale code - * @param {string} [opts.numberingSystem=null] - the numbering system - * @param {string} [opts.locObj=null] - an existing locale object to use - * @return {Array} - */ - static weekdaysFormat( - length = "long", - { locale = null, numberingSystem = null, locObj = null } = {} - ) { + }; + Info.weekdaysFormat = function weekdaysFormat(length, _temp7) { + if (length === void 0) { + length = "long"; + } + var _ref7 = _temp7 === void 0 ? {} : _temp7, _ref7$locale = _ref7.locale, locale = _ref7$locale === void 0 ? null : _ref7$locale, _ref7$numberingSystem = _ref7.numberingSystem, numberingSystem = _ref7$numberingSystem === void 0 ? null : _ref7$numberingSystem, _ref7$locObj = _ref7.locObj, locObj = _ref7$locObj === void 0 ? null : _ref7$locObj; return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); - } - - /** - * Return an array of meridiems. - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @example Info.meridiems() //=> [ 'AM', 'PM' ] - * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] - * @return {Array} - */ - static meridiems({ locale = null } = {}) { + }; + Info.meridiems = function meridiems(_temp8) { + var _ref8 = _temp8 === void 0 ? {} : _temp8, _ref8$locale = _ref8.locale, locale = _ref8$locale === void 0 ? null : _ref8$locale; return Locale.create(locale).meridiems(); - } - - /** - * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. - * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". - * @param {Object} opts - options - * @param {string} [opts.locale] - the locale code - * @example Info.eras() //=> [ 'BC', 'AD' ] - * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] - * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] - * @return {Array} - */ - static eras(length = "short", { locale = null } = {}) { + }; + Info.eras = function eras(length, _temp9) { + if (length === void 0) { + length = "short"; + } + var _ref9 = _temp9 === void 0 ? {} : _temp9, _ref9$locale = _ref9.locale, locale = _ref9$locale === void 0 ? null : _ref9$locale; return Locale.create(locale, null, "gregory").eras(length); - } - - /** - * Return the set of available features in this environment. - * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case. - * Keys: - * * `relative`: whether this environment supports relative time formatting - * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale - * @example Info.features() //=> { relative: false, localeWeek: true } - * @return {Object} - */ - static features() { - return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() }; - } - } - + }; + Info.features = function features() { + return { + relative: hasRelative(), + localeWeek: hasLocaleWeekInfo() + }; + }; + return Info; + })(); function dayDiff(earlier, later) { - const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), - ms = utcDayStart(later) - utcDayStart(earlier); + var utcDayStart = function utcDayStart(dt) { + return dt.toUTC(0, { + keepLocalTime: true + }).startOf("day").valueOf(); + }, ms = utcDayStart(later) - utcDayStart(earlier); return Math.floor(Duration.fromMillis(ms).as("days")); } - function highOrderDiffs(cursor, later, units) { - const differs = [ - ["years", (a, b) => b.year - a.year], - ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], - ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], - [ - "weeks", - (a, b) => { - const days = dayDiff(a, b); - return (days - (days % 7)) / 7; - }, - ], - ["days", dayDiff], - ]; - - const results = {}; - const earlier = cursor; - let lowestOrder, highWater; - - /* This loop tries to diff using larger units first. - If we overshoot, we backtrack and try the next smaller unit. - "cursor" starts out at the earlier timestamp and moves closer and closer to "later" - as we use smaller and smaller units. - highWater keeps track of where we would be if we added one more of the smallest unit, - this is used later to potentially convert any difference smaller than the smallest higher order unit - into a fraction of that smallest higher order unit - */ - for (const [unit, differ] of differs) { + var differs = [["years", function (a, b) { + return b.year - a.year; + }], ["quarters", function (a, b) { + return b.quarter - a.quarter + (b.year - a.year) * 4; + }], ["months", function (a, b) { + return b.month - a.month + (b.year - a.year) * 12; + }], ["weeks", function (a, b) { + var days = dayDiff(a, b); + return (days - days % 7) / 7; + }], ["days", dayDiff]]; + var results = {}; + var earlier = cursor; + var lowestOrder, highWater; + for (var _i = 0, _differs = differs; _i < _differs.length; _i++) { + var _differs$_i = _differs[_i], unit = _differs$_i[0], differ = _differs$_i[1]; if (units.indexOf(unit) >= 0) { lowestOrder = unit; - results[unit] = differ(cursor, later); highWater = earlier.plus(results); - if (highWater > later) { - // we overshot the end point, backtrack cursor by 1 results[unit]--; cursor = earlier.plus(results); - - // if we are still overshooting now, we need to backtrack again - // this happens in certain situations when diffing times in different zones, - // because this calculation ignores time zones if (cursor > later) { - // keep the "overshot by 1" around as highWater highWater = cursor; - // backtrack cursor by 1 results[unit]--; cursor = earlier.plus(results); } @@ -4831,296 +3491,268 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } } - return [cursor, results, highWater, lowestOrder]; } - - function diff (earlier, later, units, opts) { - let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); - - const remainingMillis = later - cursor; - - const lowerOrderUnits = units.filter( - (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0 - ); - + function _diff(earlier, later, units, opts) { + var _highOrderDiffs = highOrderDiffs(earlier, later, units), cursor = _highOrderDiffs[0], results = _highOrderDiffs[1], highWater = _highOrderDiffs[2], lowestOrder = _highOrderDiffs[3]; + var remainingMillis = later - cursor; + var lowerOrderUnits = units.filter(function (u) { + return ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0; + }); if (lowerOrderUnits.length === 0) { if (highWater < later) { - highWater = cursor.plus({ [lowestOrder]: 1 }); + var _cursor$plus; + highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[lowestOrder] = 1, _cursor$plus)); } - if (highWater !== cursor) { results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); } } - - const duration = Duration.fromObject(results, opts); - + var duration = Duration.fromObject(results, opts); if (lowerOrderUnits.length > 0) { - return Duration.fromMillis(remainingMillis, opts) - .shiftTo(...lowerOrderUnits) - .plus(duration); + var _Duration$fromMillis; + return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration); } else { return duration; } } - - const MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; - - function intUnit(regex, post = (i) => i) { - return { regex, deser: ([s]) => post(parseDigits(s)) }; + var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; + function intUnit(regex, post) { + if (post === void 0) { + post = function post(i) { + return i; + }; + } + return { + regex: regex, + deser: function deser(_ref) { + var s = _ref[0]; + return post(parseDigits(s)); + } + }; } - - const NBSP = String.fromCharCode(160); - const spaceOrNBSP = `[ ${NBSP}]`; - const spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); - + var NBSP = String.fromCharCode(160); + var spaceOrNBSP = "[ " + NBSP + "]"; + var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); function fixListRegex(s) { - // make dots optional and also make them literal - // make space and non breakable space characters interchangeable return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } - function stripInsensitivities(s) { - return s - .replace(/\./g, "") // ignore dots that were made optional - .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp - .toLowerCase(); + return s.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); } - function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), - deser: ([s]) => - strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex, + deser: function deser(_ref2) { + var s = _ref2[0]; + return strings.findIndex(function (i) { + return stripInsensitivities(s) === stripInsensitivities(i); + }) + startIndex; + } }; } } - function offset(regex, groups) { - return { regex, deser: ([, h, m]) => signedOffset(h, m), groups }; + return { + regex: regex, + deser: function deser(_ref3) { + var h = _ref3[1], m = _ref3[2]; + return signedOffset(h, m); + }, + groups: groups + }; } - function simple(regex) { - return { regex, deser: ([s]) => s }; + return { + regex: regex, + deser: function deser(_ref4) { + var s = _ref4[0]; + return s; + } + }; } - function escapeToken(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } - - /** - * @param token - * @param {Locale} loc - */ function unitForToken(token, loc) { - const one = digitRegex(loc), - two = digitRegex(loc, "{2}"), - three = digitRegex(loc, "{3}"), - four = digitRegex(loc, "{4}"), - six = digitRegex(loc, "{6}"), - oneOrTwo = digitRegex(loc, "{1,2}"), - oneToThree = digitRegex(loc, "{1,3}"), - oneToSix = digitRegex(loc, "{1,6}"), - oneToNine = digitRegex(loc, "{1,9}"), - twoToFour = digitRegex(loc, "{2,4}"), - fourToSix = digitRegex(loc, "{4,6}"), - literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }), - unitate = (t) => { - if (token.literal) { - return literal(t); - } - switch (t.val) { - // era - case "G": - return oneOf(loc.eras("short"), 0); - case "GG": - return oneOf(loc.eras("long"), 0); - // years - case "y": - return intUnit(oneToSix); - case "yy": - return intUnit(twoToFour, untruncateYear); - case "yyyy": - return intUnit(four); - case "yyyyy": - return intUnit(fourToSix); - case "yyyyyy": - return intUnit(six); - // months - case "M": - return intUnit(oneOrTwo); - case "MM": - return intUnit(two); - case "MMM": - return oneOf(loc.months("short", true), 1); - case "MMMM": - return oneOf(loc.months("long", true), 1); - case "L": - return intUnit(oneOrTwo); - case "LL": - return intUnit(two); - case "LLL": - return oneOf(loc.months("short", false), 1); - case "LLLL": - return oneOf(loc.months("long", false), 1); - // dates - case "d": - return intUnit(oneOrTwo); - case "dd": - return intUnit(two); - // ordinals - case "o": - return intUnit(oneToThree); - case "ooo": - return intUnit(three); - // time - case "HH": - return intUnit(two); - case "H": - return intUnit(oneOrTwo); - case "hh": - return intUnit(two); - case "h": - return intUnit(oneOrTwo); - case "mm": - return intUnit(two); - case "m": - return intUnit(oneOrTwo); - case "q": - return intUnit(oneOrTwo); - case "qq": - return intUnit(two); - case "s": - return intUnit(oneOrTwo); - case "ss": - return intUnit(two); - case "S": - return intUnit(oneToThree); - case "SSS": - return intUnit(three); - case "u": - return simple(oneToNine); - case "uu": - return simple(oneOrTwo); - case "uuu": - return intUnit(one); - // meridiem - case "a": - return oneOf(loc.meridiems(), 0); - // weekYear (k) - case "kkkk": - return intUnit(four); - case "kk": - return intUnit(twoToFour, untruncateYear); - // weekNumber (W) - case "W": - return intUnit(oneOrTwo); - case "WW": - return intUnit(two); - // weekdays - case "E": - case "c": - return intUnit(one); - case "EEE": - return oneOf(loc.weekdays("short", false), 1); - case "EEEE": - return oneOf(loc.weekdays("long", false), 1); - case "ccc": - return oneOf(loc.weekdays("short", true), 1); - case "cccc": - return oneOf(loc.weekdays("long", true), 1); - // offset/zone - case "Z": - case "ZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); - case "ZZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); - // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing - // because we don't have any way to figure out what they are - case "z": - return simple(/[a-z_+-/]{1,256}?/i); - // this special-case "token" represents a place where a macro-token expanded into a white-space literal - // in this case we accept any non-newline white-space - case " ": - return simple(/[^\S\n\r]/); - default: - return literal(t); - } + var one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = function literal(t) { + return { + regex: RegExp(escapeToken(t.val)), + deser: function deser(_ref5) { + var s = _ref5[0]; + return s; + }, + literal: true }; - - const unit = unitate(token) || { - invalidReason: MISSING_FTP, + }, unitate = function unitate(t) { + if (token.literal) { + return literal(t); + } + switch (t.val) { + case "G": + return oneOf(loc.eras("short"), 0); + case "GG": + return oneOf(loc.eras("long"), 0); + case "y": + return intUnit(oneToSix); + case "yy": + return intUnit(twoToFour, untruncateYear); + case "yyyy": + return intUnit(four); + case "yyyyy": + return intUnit(fourToSix); + case "yyyyyy": + return intUnit(six); + case "M": + return intUnit(oneOrTwo); + case "MM": + return intUnit(two); + case "MMM": + return oneOf(loc.months("short", true), 1); + case "MMMM": + return oneOf(loc.months("long", true), 1); + case "L": + return intUnit(oneOrTwo); + case "LL": + return intUnit(two); + case "LLL": + return oneOf(loc.months("short", false), 1); + case "LLLL": + return oneOf(loc.months("long", false), 1); + case "d": + return intUnit(oneOrTwo); + case "dd": + return intUnit(two); + case "o": + return intUnit(oneToThree); + case "ooo": + return intUnit(three); + case "HH": + return intUnit(two); + case "H": + return intUnit(oneOrTwo); + case "hh": + return intUnit(two); + case "h": + return intUnit(oneOrTwo); + case "mm": + return intUnit(two); + case "m": + return intUnit(oneOrTwo); + case "q": + return intUnit(oneOrTwo); + case "qq": + return intUnit(two); + case "s": + return intUnit(oneOrTwo); + case "ss": + return intUnit(two); + case "S": + return intUnit(oneToThree); + case "SSS": + return intUnit(three); + case "u": + return simple(oneToNine); + case "uu": + return simple(oneOrTwo); + case "uuu": + return intUnit(one); + case "a": + return oneOf(loc.meridiems(), 0); + case "kkkk": + return intUnit(four); + case "kk": + return intUnit(twoToFour, untruncateYear); + case "W": + return intUnit(oneOrTwo); + case "WW": + return intUnit(two); + case "E": + case "c": + return intUnit(one); + case "EEE": + return oneOf(loc.weekdays("short", false), 1); + case "EEEE": + return oneOf(loc.weekdays("long", false), 1); + case "ccc": + return oneOf(loc.weekdays("short", true), 1); + case "cccc": + return oneOf(loc.weekdays("long", true), 1); + case "Z": + case "ZZ": + return offset(new RegExp("([+-]" + oneOrTwo.source + ")(?::(" + two.source + "))?"), 2); + case "ZZZ": + return offset(new RegExp("([+-]" + oneOrTwo.source + ")(" + two.source + ")?"), 2); + case "z": + return simple(/[a-z_+-/]{1,256}?/i); + case " ": + return simple(/[^\S\n\r]/); + default: + return literal(t); + } }; - + var unit = unitate(token) || ({ + invalidReason: MISSING_FTP + }); unit.token = token; - return unit; } - - const partTypeStyleToTokenVal = { + var partTypeStyleToTokenVal = { year: { "2-digit": "yy", - numeric: "yyyyy", + numeric: "yyyyy" }, month: { numeric: "M", "2-digit": "MM", short: "MMM", - long: "MMMM", + long: "MMMM" }, day: { numeric: "d", - "2-digit": "dd", + "2-digit": "dd" }, weekday: { short: "EEE", - long: "EEEE", + long: "EEEE" }, dayperiod: "a", dayPeriod: "a", hour12: { numeric: "h", - "2-digit": "hh", + "2-digit": "hh" }, hour24: { numeric: "H", - "2-digit": "HH", + "2-digit": "HH" }, minute: { numeric: "m", - "2-digit": "mm", + "2-digit": "mm" }, second: { numeric: "s", - "2-digit": "ss", + "2-digit": "ss" }, timeZoneName: { long: "ZZZZZ", - short: "ZZZ", - }, + short: "ZZZ" + } }; - function tokenForPart(part, formatOpts, resolvedOpts) { - const { type, value } = part; - + var type = part.type, value = part.value; if (type === "literal") { - const isSpace = /^\s+$/.test(value); + var isSpace = (/^\s+$/).test(value); return { literal: !isSpace, - val: isSpace ? " " : value, + val: isSpace ? " " : value }; } - - const style = formatOpts[type]; - - // The user might have explicitly specified hour12 or hourCycle - // if so, respect their decision - // if not, refer back to the resolvedOpts, which are based on the locale - let actualType = type; + var style = formatOpts[type]; + var actualType = type; if (type === "hour") { if (formatOpts.hour12 != null) { actualType = formatOpts.hour12 ? "hour12" : "hour24"; @@ -5131,41 +3763,37 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; actualType = "hour24"; } } else { - // tokens only differentiate between 24 hours or not, - // so we do not need to check hourCycle here, which is less supported anyways actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; } } - let val = partTypeStyleToTokenVal[actualType]; + var val = partTypeStyleToTokenVal[actualType]; if (typeof val === "object") { val = val[style]; } - if (val) { return { literal: false, - val, + val: val }; } - return undefined; } - function buildRegex(units) { - const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); - return [`^${re}$`, units]; + var re = units.map(function (u) { + return u.regex; + }).reduce(function (f, r) { + return f + "(" + r.source + ")"; + }, ""); + return ["^" + re + "$", units]; } - function match(input, regex, handlers) { - const matches = input.match(regex); - + var matches = input.match(regex); if (matches) { - const all = {}; - let matchIndex = 1; - for (const i in handlers) { + var all = {}; + var matchIndex = 1; + for (var i in handlers) { if (hasOwnProperty(handlers, i)) { - const h = handlers[i], - groups = h.groups ? h.groups + 1 : 1; + var h = handlers[i], groups = h.groups ? h.groups + 1 : 1; if (!h.literal && h.token) { all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); } @@ -5177,9 +3805,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return [matches, {}]; } } - function dateTimeFromMatches(matches) { - const toField = (token) => { + var toField = function toField(token) { switch (token) { case "S": return "millisecond"; @@ -5212,24 +3839,20 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return null; } }; - - let zone = null; - let specificOffset; + var zone = null; + var specificOffset; if (!isUndefined(matches.z)) { zone = IANAZone.create(matches.z); } - if (!isUndefined(matches.Z)) { if (!zone) { zone = new FixedOffsetZone(matches.Z); } specificOffset = matches.Z; } - if (!isUndefined(matches.q)) { matches.M = (matches.q - 1) * 3 + 1; } - if (!isUndefined(matches.h)) { if (matches.h < 12 && matches.a === 1) { matches.h += 12; @@ -5237,211 +3860,166 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; matches.h = 0; } } - if (matches.G === 0 && matches.y) { matches.y = -matches.y; } - if (!isUndefined(matches.u)) { matches.S = parseMillis(matches.u); } - - const vals = Object.keys(matches).reduce((r, k) => { - const f = toField(k); + var vals = Object.keys(matches).reduce(function (r, k) { + var f = toField(k); if (f) { r[f] = matches[k]; } - return r; }, {}); - return [vals, zone, specificOffset]; } - - let dummyDateTimeCache = null; - + var dummyDateTimeCache = null; function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } - return dummyDateTimeCache; } - function maybeExpandMacroToken(token, locale) { if (token.literal) { return token; } - - const formatOpts = Formatter.macroTokenToFormatOpts(token.val); - const tokens = formatOptsToTokens(formatOpts, locale); - + var formatOpts = Formatter.macroTokenToFormatOpts(token.val); + var tokens = formatOptsToTokens(formatOpts, locale); if (tokens == null || tokens.includes(undefined)) { return token; } - return tokens; } - function expandMacroTokens(tokens, locale) { - return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale))); + var _Array$prototype; + return (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, tokens.map(function (t) { + return maybeExpandMacroToken(t, locale); + })); } - - /** - * @private - */ - - class TokenParser { - constructor(locale, format) { + var TokenParser = (function () { + function TokenParser(locale, format) { this.locale = locale; this.format = format; this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale); - this.units = this.tokens.map((t) => unitForToken(t, locale)); - this.disqualifyingUnit = this.units.find((t) => t.invalidReason); - + this.units = this.tokens.map(function (t) { + return unitForToken(t, locale); + }); + this.disqualifyingUnit = this.units.find(function (t) { + return t.invalidReason; + }); if (!this.disqualifyingUnit) { - const [regexString, handlers] = buildRegex(this.units); + var _buildRegex = buildRegex(this.units), regexString = _buildRegex[0], handlers = _buildRegex[1]; this.regex = RegExp(regexString, "i"); this.handlers = handlers; } } - - explainFromTokens(input) { + var _proto = TokenParser.prototype; + _proto.explainFromTokens = function explainFromTokens(input) { if (!this.isValid) { - return { input, tokens: this.tokens, invalidReason: this.invalidReason }; + return { + input: input, + tokens: this.tokens, + invalidReason: this.invalidReason + }; } else { - const [rawMatches, matches] = match(input, this.regex, this.handlers), - [result, zone, specificOffset] = matches - ? dateTimeFromMatches(matches) - : [null, null, undefined]; + var _match = match(input, this.regex, this.handlers), rawMatches = _match[0], matches = _match[1], _ref6 = matches ? dateTimeFromMatches(matches) : [null, null, undefined], result = _ref6[0], zone = _ref6[1], specificOffset = _ref6[2]; if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { - throw new ConflictingSpecificationError( - "Can't include meridiem when specifying 24-hour format" - ); + throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); } return { - input, + input: input, tokens: this.tokens, regex: this.regex, - rawMatches, - matches, - result, - zone, - specificOffset, + rawMatches: rawMatches, + matches: matches, + result: result, + zone: zone, + specificOffset: specificOffset }; } - } - - get isValid() { - return !this.disqualifyingUnit; - } - - get invalidReason() { - return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; - } - } - + }; + _createClass(TokenParser, [{ + key: "isValid", + get: function get() { + return !this.disqualifyingUnit; + } + }, { + key: "invalidReason", + get: function get() { + return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; + } + }]); + return TokenParser; + })(); function explainFromTokens(locale, input, format) { - const parser = new TokenParser(locale, format); + var parser = new TokenParser(locale, format); return parser.explainFromTokens(input); } - function parseFromTokens(locale, input, format) { - const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); + var _explainFromTokens = explainFromTokens(locale, input, format), result = _explainFromTokens.result, zone = _explainFromTokens.zone, specificOffset = _explainFromTokens.specificOffset, invalidReason = _explainFromTokens.invalidReason; return [result, zone, specificOffset, invalidReason]; } - function formatOptsToTokens(formatOpts, locale) { if (!formatOpts) { return null; } - - const formatter = Formatter.create(locale, formatOpts); - const df = formatter.dtFormatter(getDummyDateTime()); - const parts = df.formatToParts(); - const resolvedOpts = df.resolvedOptions(); - return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts)); + var formatter = Formatter.create(locale, formatOpts); + var df = formatter.dtFormatter(getDummyDateTime()); + var parts = df.formatToParts(); + var resolvedOpts = df.resolvedOptions(); + return parts.map(function (p) { + return tokenForPart(p, formatOpts, resolvedOpts); + }); } - - const INVALID = "Invalid DateTime"; - const MAX_DATE = 8.64e15; - + var INVALID = "Invalid DateTime"; + var MAX_DATE = 8640000000000000; function unsupportedZone(zone) { - return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); + return new Invalid("unsupported zone", "the zone \"" + zone.name + "\" is not supported"); } - - // we cache week data on the DT object and this intermediates the cache - /** - * @param {DateTime} dt - */ function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } return dt.weekData; } - - /** - * @param {DateTime} dt - */ function possiblyCachedLocalWeekData(dt) { if (dt.localWeekData === null) { - dt.localWeekData = gregorianToWeek( - dt.c, - dt.loc.getMinDaysInFirstWeek(), - dt.loc.getStartOfWeek() - ); + dt.localWeekData = gregorianToWeek(dt.c, dt.loc.getMinDaysInFirstWeek(), dt.loc.getStartOfWeek()); } return dt.localWeekData; } - - // clone really means, "make a new object with these modifications". all "setters" really use this - // to create a new object while only changing some of the properties function clone(inst, alts) { - const current = { + var current = { ts: inst.ts, zone: inst.zone, c: inst.c, o: inst.o, loc: inst.loc, - invalid: inst.invalid, + invalid: inst.invalid }; - return new DateTime({ ...current, ...alts, old: current }); + return new DateTime(_extends({}, current, alts, { + old: current + })); } - - // find the right offset a given local time. The o input is our guess, which determines which - // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) function fixOffset(localTS, o, tz) { - // Our UTC time is just a guess because our offset is just a guess - let utcGuess = localTS - o * 60 * 1000; - - // Test whether the zone matches the offset for this ts - const o2 = tz.offset(utcGuess); - - // If so, offset didn't change and we're done + var utcGuess = localTS - o * 60 * 1000; + var o2 = tz.offset(utcGuess); if (o === o2) { return [utcGuess, o]; } - - // If not, change the ts by the difference in the offset utcGuess -= (o2 - o) * 60 * 1000; - - // If that gives us the local time we want, we're done - const o3 = tz.offset(utcGuess); + var o3 = tz.offset(utcGuess); if (o2 === o3) { return [utcGuess, o2]; } - - // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; } - - // convert an epoch timestamp into a calendar object with the given offset function tsToObj(ts, offset) { ts += offset * 60 * 1000; - - const d = new Date(ts); - + var d = new Date(ts); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, @@ -5449,89 +4027,64 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), - millisecond: d.getUTCMilliseconds(), + millisecond: d.getUTCMilliseconds() }; } - - // convert a calendar object to a epoch timestamp function objToTS(obj, offset, zone) { return fixOffset(objToLocalTS(obj), offset, zone); } - - // create a new DT instance by adding a duration, adjusting for DSTs function adjustTime(inst, dur) { - const oPre = inst.o, - year = inst.c.year + Math.trunc(dur.years), - month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, - c = { - ...inst.c, - year, - month, - day: - Math.min(inst.c.day, daysInMonth(year, month)) + - Math.trunc(dur.days) + - Math.trunc(dur.weeks) * 7, - }, - millisToAdd = Duration.fromObject({ - years: dur.years - Math.trunc(dur.years), - quarters: dur.quarters - Math.trunc(dur.quarters), - months: dur.months - Math.trunc(dur.months), - weeks: dur.weeks - Math.trunc(dur.weeks), - days: dur.days - Math.trunc(dur.days), - hours: dur.hours, - minutes: dur.minutes, - seconds: dur.seconds, - milliseconds: dur.milliseconds, - }).as("milliseconds"), - localTS = objToLocalTS(c); - - let [ts, o] = fixOffset(localTS, oPre, inst.zone); - + var oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = _extends({}, inst.c, { + year: year, + month: month, + day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 + }), millisToAdd = Duration.fromObject({ + years: dur.years - Math.trunc(dur.years), + quarters: dur.quarters - Math.trunc(dur.quarters), + months: dur.months - Math.trunc(dur.months), + weeks: dur.weeks - Math.trunc(dur.weeks), + days: dur.days - Math.trunc(dur.days), + hours: dur.hours, + minutes: dur.minutes, + seconds: dur.seconds, + milliseconds: dur.milliseconds + }).as("milliseconds"), localTS = objToLocalTS(c); + var _fixOffset = fixOffset(localTS, oPre, inst.zone), ts = _fixOffset[0], o = _fixOffset[1]; if (millisToAdd !== 0) { ts += millisToAdd; - // that could have changed the offset by going over a DST, but we want to keep the ts the same o = inst.zone.offset(ts); } - - return { ts, o }; + return { + ts: ts, + o: o + }; } - - // helper useful in turning the results of parsing into real dates - // by handling the zone options function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) { - const { setZone, zone } = opts; - if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) { - const interpretationZone = parsedZone || zone, - inst = DateTime.fromObject(parsed, { - ...opts, - zone: interpretationZone, - specificOffset, - }); + var setZone = opts.setZone, zone = opts.zone; + if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { + var interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, _extends({}, opts, { + zone: interpretationZone, + specificOffset: specificOffset + })); return setZone ? inst : inst.setZone(zone); } else { - return DateTime.invalid( - new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`) - ); + return DateTime.invalid(new Invalid("unparsable", "the input \"" + text + "\" can't be parsed as " + format)); } } - - // if you want to output a technical format (e.g. RFC 2822), this helper - // helps handle the details - function toTechFormat(dt, format, allowZ = true) { - return dt.isValid - ? Formatter.create(Locale.create("en-US"), { - allowZ, - forceSimple: true, - }).formatDateTimeFromString(dt, format) - : null; + function toTechFormat(dt, format, allowZ) { + if (allowZ === void 0) { + allowZ = true; + } + return dt.isValid ? Formatter.create(Locale.create("en-US"), { + allowZ: allowZ, + forceSimple: true + }).formatDateTimeFromString(dt, format) : null; } - - function toISODate(o, extended) { - const longFormat = o.c.year > 9999 || o.c.year < 0; - let c = ""; + function _toISODate(o, extended) { + var longFormat = o.c.year > 9999 || o.c.year < 0; + var c = ""; if (longFormat && o.c.year >= 0) c += "+"; c += padStart(o.c.year, longFormat ? 6 : 4); - if (extended) { c += "-"; c += padStart(o.c.month); @@ -5543,16 +4096,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return c; } - - function toISOTime( - o, - extended, - suppressSeconds, - suppressMilliseconds, - includeOffset, - extendedZone - ) { - let c = padStart(o.c.hour); + function _toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { + var c = padStart(o.c.hour); if (extended) { c += ":"; c += padStart(o.c.minute); @@ -5562,16 +4107,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { c += padStart(o.c.minute); } - if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { c += padStart(o.c.second); - if (o.c.millisecond !== 0 || !suppressMilliseconds) { c += "."; c += padStart(o.c.millisecond, 3); } } - if (includeOffset) { if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { c += "Z"; @@ -5587,54 +4129,35 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; c += padStart(Math.trunc(o.o % 60)); } } - if (extendedZone) { c += "[" + o.zone.ianaName + "]"; } return c; } - - // defaults for unspecified units in the supported calendars - const defaultUnitValues = { - month: 1, - day: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0, - }, - defaultWeekUnitValues = { - weekNumber: 1, - weekday: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0, - }, - defaultOrdinalUnitValues = { - ordinal: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0, - }; - - // Units in the supported calendars, sorted by bigness - const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"], - orderedWeekUnits = [ - "weekYear", - "weekNumber", - "weekday", - "hour", - "minute", - "second", - "millisecond", - ], - orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; - - // standardize case and plurality in units + var defaultUnitValues = { + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }, defaultWeekUnitValues = { + weekNumber: 1, + weekday: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }, defaultOrdinalUnitValues = { + ordinal: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"], orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"], orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; function normalizeUnit(unit) { - const normalized = { + var normalized = ({ year: "year", years: "year", month: "month", @@ -5658,14 +4181,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; weeknumbers: "weekNumber", weekyear: "weekYear", weekyears: "weekYear", - ordinal: "ordinal", - }[unit.toLowerCase()]; - + ordinal: "ordinal" + })[unit.toLowerCase()]; if (!normalized) throw new InvalidUnitError(unit); - return normalized; } - function normalizeUnitWithLocalWeeks(unit) { switch (unit.toLowerCase()) { case "localweekday": @@ -5681,105 +4201,75 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return normalizeUnit(unit); } } - - // cache offsets for zones based on the current timestamp when this function is - // first called. When we are handling a datetime from components like (year, - // month, day, hour) in a time zone, we need a guess about what the timezone - // offset is so that we can convert into a UTC timestamp. One way is to find the - // offset of now in the zone. The actual date may have a different offset (for - // example, if we handle a date in June while we're in December in a zone that - // observes DST), but we can check and adjust that. - // - // When handling many dates, calculating the offset for now every time is - // expensive. It's just a guess, so we can cache the offset to use even if we - // are right on a time change boundary (we'll just correct in the other - // direction). Using a timestamp from first read is a slight optimization for - // handling dates close to the current date, since those dates will usually be - // in the same offset (we could set the timestamp statically, instead). We use a - // single timestamp for all zones to make things a bit more predictable. - // - // This is safe for quickDT (used by local() and utc()) because we don't fill in - // higher-order units from tsNow (as we do in fromObject, this requires that - // offset is calculated from tsNow). function guessOffsetForZone(zone) { if (!zoneOffsetGuessCache[zone]) { if (zoneOffsetTs === undefined) { zoneOffsetTs = Settings.now(); } - zoneOffsetGuessCache[zone] = zone.offset(zoneOffsetTs); } return zoneOffsetGuessCache[zone]; } - - // this is a dumbed down version of fromObject() that runs about 60% faster - // but doesn't do any validation, makes a bunch of assumptions about what units - // are present, and so on. function quickDT(obj, opts) { - const zone = normalizeZone(opts.zone, Settings.defaultZone); + var zone = normalizeZone(opts.zone, Settings.defaultZone); if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } - - const loc = Locale.fromObject(opts); - - let ts, o; - - // assume we have the higher-order units + var loc = Locale.fromObject(opts); + var ts, o; if (!isUndefined(obj.year)) { - for (const u of orderedUnits) { + for (var _i = 0, _orderedUnits = orderedUnits; _i < _orderedUnits.length; _i++) { + var u = _orderedUnits[_i]; if (isUndefined(obj[u])) { obj[u] = defaultUnitValues[u]; } } - - const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); + var invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalid) { return DateTime.invalid(invalid); } - - const offsetProvis = guessOffsetForZone(zone); - [ts, o] = objToTS(obj, offsetProvis, zone); + var offsetProvis = guessOffsetForZone(zone); + var _objToTS = objToTS(obj, offsetProvis, zone); + ts = _objToTS[0]; + o = _objToTS[1]; } else { ts = Settings.now(); } - - return new DateTime({ ts, zone, loc, o }); + return new DateTime({ + ts: ts, + zone: zone, + loc: loc, + o: o + }); } - function diffRelative(start, end, opts) { - const round = isUndefined(opts.round) ? true : opts.round, - format = (c, unit) => { - c = roundTo(c, round || opts.calendary ? 0 : 2, true); - const formatter = end.loc.clone(opts).relFormatter(opts); - return formatter.format(c, unit); - }, - differ = (unit) => { - if (opts.calendary) { - if (!end.hasSame(start, unit)) { - return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); - } else return 0; - } else { - return end.diff(start, unit).get(unit); - } - }; - + var round = isUndefined(opts.round) ? true : opts.round, format = function format(c, unit) { + c = roundTo(c, round || opts.calendary ? 0 : 2, true); + var formatter = end.loc.clone(opts).relFormatter(opts); + return formatter.format(c, unit); + }, differ = function differ(unit) { + if (opts.calendary) { + if (!end.hasSame(start, unit)) { + return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); + } else return 0; + } else { + return end.diff(start, unit).get(unit); + } + }; if (opts.unit) { return format(differ(opts.unit), opts.unit); } - - for (const unit of opts.units) { - const count = differ(unit); + for (var _iterator = _createForOfIteratorHelperLoose(opts.units), _step; !(_step = _iterator()).done; ) { + var unit = _step.value; + var count = differ(unit); if (Math.abs(count) >= 1) { return format(count, unit); } } return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); } - function lastOpts(argList) { - let opts = {}, - args; + var opts = {}, args; if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { opts = argList[argList.length - 1]; args = Array.from(argList).slice(0, argList.length - 1); @@ -5788,332 +4278,134 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return [opts, args]; } - - /** - * Timestamp to use for cached zone offset guesses (exposed for test) - */ - let zoneOffsetTs; - /** - * Cache for zone offset guesses (exposed for test). - * - * This optimizes quickDT via guessOffsetForZone to avoid repeated calls of - * zone.offset(). - */ - let zoneOffsetGuessCache = {}; - - /** - * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. - * - * A DateTime comprises of: - * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch. - * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone). - * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`. - * - * Here is a brief overview of the most commonly used functionality it provides: - * - * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}. - * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month}, - * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors. - * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors. - * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors. - * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}. - * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}. - * - * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. - */ - class DateTime { - /** - * @access private - */ - constructor(config) { - const zone = config.zone || Settings.defaultZone; - - let invalid = - config.invalid || - (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || - (!zone.isValid ? unsupportedZone(zone) : null); - /** - * @access private - */ + var zoneOffsetTs; + var zoneOffsetGuessCache = {}; + var DateTime = (function (_Symbol$for) { + function DateTime(config) { + var zone = config.zone || Settings.defaultZone; + var invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; - - let c = null, - o = null; + var c = null, o = null; if (!invalid) { - const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); - + var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); if (unchanged) { - [c, o] = [config.old.c, config.old.o]; + var _ref = [config.old.c, config.old.o]; + c = _ref[0]; + o = _ref[1]; } else { - // If an offset has been passed and we have not been called from - // clone(), we can trust it and avoid the offset calculation. - const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts); + var ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts); c = tsToObj(this.ts, ot); invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; c = invalid ? null : c; o = invalid ? null : ot; } } - - /** - * @access private - */ this._zone = zone; - /** - * @access private - */ this.loc = config.loc || Locale.create(); - /** - * @access private - */ this.invalid = invalid; - /** - * @access private - */ this.weekData = null; - /** - * @access private - */ this.localWeekData = null; - /** - * @access private - */ this.c = c; - /** - * @access private - */ this.o = o; - /** - * @access private - */ this.isLuxonDateTime = true; } - - // CONSTRUCT - - /** - * Create a DateTime for the current instant, in the system's time zone. - * - * Use Settings to override these default values if needed. - * @example DateTime.now().toISO() //~> now in the ISO format - * @return {DateTime} - */ - static now() { + DateTime.now = function now() { return new DateTime({}); - } - - /** - * Create a local DateTime - * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used - * @param {number} [month=1] - The month, 1-indexed - * @param {number} [day=1] - The day of the month, 1-indexed - * @param {number} [hour=0] - The hour of the day, in 24-hour time - * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 - * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 - * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 - * @example DateTime.local() //~> now - * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time - * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 - * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 - * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale - * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 - * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC - * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 - * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 - * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 - * @return {DateTime} - */ - static local() { - const [opts, args] = lastOpts(arguments), - [year, month, day, hour, minute, second, millisecond] = args; - return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); - } - - /** - * Create a DateTime in UTC - * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used - * @param {number} [month=1] - The month, 1-indexed - * @param {number} [day=1] - The day of the month - * @param {number} [hour=0] - The hour of the day, in 24-hour time - * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 - * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 - * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 - * @param {Object} options - configuration options for the DateTime - * @param {string} [options.locale] - a locale to set on the resulting DateTime instance - * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance - * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance - * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance - * @example DateTime.utc() //~> now - * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z - * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z - * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z - * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z - * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z - * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale - * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z - * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale - * @return {DateTime} - */ - static utc() { - const [opts, args] = lastOpts(arguments), - [year, month, day, hour, minute, second, millisecond] = args; - + }; + DateTime.local = function local() { + var _lastOpts = lastOpts(arguments), opts = _lastOpts[0], args = _lastOpts[1], year = args[0], month = args[1], day = args[2], hour = args[3], minute = args[4], second = args[5], millisecond = args[6]; + return quickDT({ + year: year, + month: month, + day: day, + hour: hour, + minute: minute, + second: second, + millisecond: millisecond + }, opts); + }; + DateTime.utc = function utc() { + var _lastOpts2 = lastOpts(arguments), opts = _lastOpts2[0], args = _lastOpts2[1], year = args[0], month = args[1], day = args[2], hour = args[3], minute = args[4], second = args[5], millisecond = args[6]; opts.zone = FixedOffsetZone.utcInstance; - return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); - } - - /** - * Create a DateTime from a JavaScript Date object. Uses the default zone. - * @param {Date} date - a JavaScript Date object - * @param {Object} options - configuration options for the DateTime - * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into - * @return {DateTime} - */ - static fromJSDate(date, options = {}) { - const ts = isDate(date) ? date.valueOf() : NaN; + return quickDT({ + year: year, + month: month, + day: day, + hour: hour, + minute: minute, + second: second, + millisecond: millisecond + }, opts); + }; + DateTime.fromJSDate = function fromJSDate(date, options) { + if (options === void 0) { + options = {}; + } + var ts = isDate(date) ? date.valueOf() : NaN; if (Number.isNaN(ts)) { return DateTime.invalid("invalid input"); } - - const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); + var zoneToUse = normalizeZone(options.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } - return new DateTime({ ts: ts, zone: zoneToUse, - loc: Locale.fromObject(options), + loc: Locale.fromObject(options) }); - } - - /** - * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. - * @param {number} milliseconds - a number of milliseconds since 1970 UTC - * @param {Object} options - configuration options for the DateTime - * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into - * @param {string} [options.locale] - a locale to set on the resulting DateTime instance - * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance - * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance - * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance - * @return {DateTime} - */ - static fromMillis(milliseconds, options = {}) { + }; + DateTime.fromMillis = function fromMillis(milliseconds, options) { + if (options === void 0) { + options = {}; + } if (!isNumber(milliseconds)) { - throw new InvalidArgumentError( - `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}` - ); + throw new InvalidArgumentError("fromMillis requires a numerical input, but received a " + typeof milliseconds + " with value " + milliseconds); } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { - // this isn't perfect because we can still end up out of range because of additional shifting, but it's a start return DateTime.invalid("Timestamp out of range"); } else { return new DateTime({ ts: milliseconds, zone: normalizeZone(options.zone, Settings.defaultZone), - loc: Locale.fromObject(options), + loc: Locale.fromObject(options) }); } - } - - /** - * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. - * @param {number} seconds - a number of seconds since 1970 UTC - * @param {Object} options - configuration options for the DateTime - * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into - * @param {string} [options.locale] - a locale to set on the resulting DateTime instance - * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance - * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance - * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance - * @return {DateTime} - */ - static fromSeconds(seconds, options = {}) { + }; + DateTime.fromSeconds = function fromSeconds(seconds, options) { + if (options === void 0) { + options = {}; + } if (!isNumber(seconds)) { throw new InvalidArgumentError("fromSeconds requires a numerical input"); } else { return new DateTime({ ts: seconds * 1000, zone: normalizeZone(options.zone, Settings.defaultZone), - loc: Locale.fromObject(options), + loc: Locale.fromObject(options) }); } - } - - /** - * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. - * @param {Object} obj - the object to create the DateTime from - * @param {number} obj.year - a year, such as 1987 - * @param {number} obj.month - a month, 1-12 - * @param {number} obj.day - a day of the month, 1-31, depending on the month - * @param {number} obj.ordinal - day of the year, 1-365 or 366 - * @param {number} obj.weekYear - an ISO week year - * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year - * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday - * @param {number} obj.localWeekYear - a week year, according to the locale - * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale - * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale - * @param {number} obj.hour - hour of the day, 0-23 - * @param {number} obj.minute - minute of the hour, 0-59 - * @param {number} obj.second - second of the minute, 0-59 - * @param {number} obj.millisecond - millisecond of the second, 0-999 - * @param {Object} opts - options for creating this DateTime - * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() - * @param {string} [opts.locale='system\'s locale'] - a locale to set on the resulting DateTime instance - * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance - * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance - * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance - * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' - * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' - * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 - * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }), - * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' }) - * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' }) - * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' - * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26' - * @return {DateTime} - */ - static fromObject(obj, opts = {}) { - obj = obj || {}; - const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); + }; + DateTime.fromObject = function fromObject(obj, opts) { + if (opts === void 0) { + opts = {}; + } + obj = obj || ({}); + var zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } - - const loc = Locale.fromObject(opts); - const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); - const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc); - - const tsNow = Settings.now(), - offsetProvis = !isUndefined(opts.specificOffset) - ? opts.specificOffset - : zoneToUse.offset(tsNow), - containsOrdinal = !isUndefined(normalized.ordinal), - containsGregorYear = !isUndefined(normalized.year), - containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), - containsGregor = containsGregorYear || containsGregorMD, - definiteWeekDef = normalized.weekYear || normalized.weekNumber; - - // cases: - // just a weekday -> this week's instance of that weekday, no worries - // (gregorian data or ordinal) + (weekYear or weekNumber) -> error - // (gregorian month or day) + ordinal -> error - // otherwise just use weeks or ordinals or gregorian, depending on what's specified - + var loc = Locale.fromObject(opts); + var normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); + var _usesLocalWeekValues = usesLocalWeekValues(normalized, loc), minDaysInFirstWeek = _usesLocalWeekValues.minDaysInFirstWeek, startOfWeek = _usesLocalWeekValues.startOfWeek; + var tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; if ((containsGregor || containsOrdinal) && definiteWeekDef) { - throw new ConflictingSpecificationError( - "Can't mix weekYear/weekNumber units with year/month/day or ordinals" - ); + throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } - if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } - - const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor); - - // configure ourselves to deal with gregorian dates or week stuff - let units, - defaultValues, - objNow = tsToObj(tsNow, offsetProvis); + var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; + var units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; @@ -6126,11 +4418,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; units = orderedUnits; defaultValues = defaultUnitValues; } - - // set default values for missing stuff - let foundFirst = false; - for (const u of units) { - const v = normalized[u]; + var foundFirst = false; + for (var _iterator2 = _createForOfIteratorHelperLoose(units), _step2; !(_step2 = _iterator2()).done; ) { + var u = _step2.value; + var v = normalized[u]; if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { @@ -6139,887 +4430,271 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; normalized[u] = objNow[u]; } } - - // make sure the values we have are in range - const higherOrderInvalid = useWeekData - ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) - : containsOrdinal - ? hasInvalidOrdinalData(normalized) - : hasInvalidGregorianData(normalized), - invalid = higherOrderInvalid || hasInvalidTimeData(normalized); - + var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); if (invalid) { return DateTime.invalid(invalid); } - - // compute the actual time - const gregorian = useWeekData - ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) - : containsOrdinal - ? ordinalToGregorian(normalized) - : normalized, - [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), - inst = new DateTime({ - ts: tsFinal, - zone: zoneToUse, - o: offsetFinal, - loc, - }); - - // gregorian data + weekday serves only to validate + var gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, _objToTS2 = objToTS(gregorian, offsetProvis, zoneToUse), tsFinal = _objToTS2[0], offsetFinal = _objToTS2[1], inst = new DateTime({ + ts: tsFinal, + zone: zoneToUse, + o: offsetFinal, + loc: loc + }); if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { - return DateTime.invalid( - "mismatched weekday", - `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}` - ); + return DateTime.invalid("mismatched weekday", "you can't specify both a weekday of " + normalized.weekday + " and a date of " + inst.toISO()); } - if (!inst.isValid) { return DateTime.invalid(inst.invalid); } - return inst; - } - - /** - * Create a DateTime from an ISO 8601 string - * @param {string} text - the ISO string - * @param {Object} opts - options to affect the creation - * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone - * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one - * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance - * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance - * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance - * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance - * @example DateTime.fromISO('2016-05-25T09:08:34.123') - * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') - * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) - * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) - * @example DateTime.fromISO('2016-W05-4') - * @return {DateTime} - */ - static fromISO(text, opts = {}) { - const [vals, parsedZone] = parseISODate(text); + }; + DateTime.fromISO = function fromISO(text, opts) { + if (opts === void 0) { + opts = {}; + } + var _parseISODate = parseISODate(text), vals = _parseISODate[0], parsedZone = _parseISODate[1]; return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); - } - - /** - * Create a DateTime from an RFC 2822 string - * @param {string} text - the RFC 2822 string - * @param {Object} opts - options to affect the creation - * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. - * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one - * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance - * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance - * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance - * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance - * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') - * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') - * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') - * @return {DateTime} - */ - static fromRFC2822(text, opts = {}) { - const [vals, parsedZone] = parseRFC2822Date(text); + }; + DateTime.fromRFC2822 = function fromRFC2822(text, opts) { + if (opts === void 0) { + opts = {}; + } + var _parseRFC2822Date = parseRFC2822Date(text), vals = _parseRFC2822Date[0], parsedZone = _parseRFC2822Date[1]; return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); - } - - /** - * Create a DateTime from an HTTP header date - * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 - * @param {string} text - the HTTP header date - * @param {Object} opts - options to affect the creation - * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. - * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. - * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance - * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance - * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance - * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance - * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') - * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') - * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') - * @return {DateTime} - */ - static fromHTTP(text, opts = {}) { - const [vals, parsedZone] = parseHTTPDate(text); + }; + DateTime.fromHTTP = function fromHTTP(text, opts) { + if (opts === void 0) { + opts = {}; + } + var _parseHTTPDate = parseHTTPDate(text), vals = _parseHTTPDate[0], parsedZone = _parseHTTPDate[1]; return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); - } - - /** - * Create a DateTime from an input string and format string. - * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). - * @param {string} text - the string to parse - * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) - * @param {Object} opts - options to affect the creation - * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone - * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one - * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale - * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system - * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance - * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance - * @return {DateTime} - */ - static fromFormat(text, fmt, opts = {}) { + }; + DateTime.fromFormat = function fromFormat(text, fmt, opts) { + if (opts === void 0) { + opts = {}; + } if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } - - const { locale = null, numberingSystem = null } = opts, - localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true, - }), - [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt); + var _opts = opts, _opts$locale = _opts.locale, locale = _opts$locale === void 0 ? null : _opts$locale, _opts$numberingSystem = _opts.numberingSystem, numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem, localeToUse = Locale.fromOpts({ + locale: locale, + numberingSystem: numberingSystem, + defaultToEN: true + }), _parseFromTokens = parseFromTokens(localeToUse, text, fmt), vals = _parseFromTokens[0], parsedZone = _parseFromTokens[1], specificOffset = _parseFromTokens[2], invalid = _parseFromTokens[3]; if (invalid) { return DateTime.invalid(invalid); } else { - return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); + return parseDataToDateTime(vals, parsedZone, opts, "format " + fmt, text, specificOffset); + } + }; + DateTime.fromString = function fromString(text, fmt, opts) { + if (opts === void 0) { + opts = {}; } - } - - /** - * @deprecated use fromFormat instead - */ - static fromString(text, fmt, opts = {}) { return DateTime.fromFormat(text, fmt, opts); - } - - /** - * Create a DateTime from a SQL date, time, or datetime - * Defaults to en-US if no locale has been specified, regardless of the system's locale - * @param {string} text - the string to parse - * @param {Object} opts - options to affect the creation - * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone - * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one - * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale - * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system - * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance - * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance - * @example DateTime.fromSQL('2017-05-15') - * @example DateTime.fromSQL('2017-05-15 09:12:34') - * @example DateTime.fromSQL('2017-05-15 09:12:34.342') - * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') - * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') - * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) - * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) - * @example DateTime.fromSQL('09:12:34.342') - * @return {DateTime} - */ - static fromSQL(text, opts = {}) { - const [vals, parsedZone] = parseSQL(text); + }; + DateTime.fromSQL = function fromSQL(text, opts) { + if (opts === void 0) { + opts = {}; + } + var _parseSQL = parseSQL(text), vals = _parseSQL[0], parsedZone = _parseSQL[1]; return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); - } - - /** - * Create an invalid DateTime. - * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent. - * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information - * @return {DateTime} - */ - static invalid(reason, explanation = null) { + }; + DateTime.invalid = function invalid(reason, explanation) { + if (explanation === void 0) { + explanation = null; + } if (!reason) { throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); } - - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - + var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDateTimeError(invalid); } else { - return new DateTime({ invalid }); + return new DateTime({ + invalid: invalid + }); } - } - - /** - * Check if an object is an instance of DateTime. Works across context boundaries - * @param {object} o - * @return {boolean} - */ - static isDateTime(o) { - return (o && o.isLuxonDateTime) || false; - } - - /** - * Produce the format string for a set of options - * @param formatOpts - * @param localeOpts - * @returns {string} - */ - static parseFormatForOpts(formatOpts, localeOpts = {}) { - const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); - return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join(""); - } - - /** - * Produce the the fully expanded format token for the locale - * Does NOT quote characters, so quoted tokens will not round trip correctly - * @param fmt - * @param localeOpts - * @returns {string} - */ - static expandFormat(fmt, localeOpts = {}) { - const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); - return expanded.map((t) => t.val).join(""); - } - - static resetCache() { + }; + DateTime.isDateTime = function isDateTime(o) { + return o && o.isLuxonDateTime || false; + }; + DateTime.parseFormatForOpts = function parseFormatForOpts(formatOpts, localeOpts) { + if (localeOpts === void 0) { + localeOpts = {}; + } + var tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); + return !tokenList ? null : tokenList.map(function (t) { + return t ? t.val : null; + }).join(""); + }; + DateTime.expandFormat = function expandFormat(fmt, localeOpts) { + if (localeOpts === void 0) { + localeOpts = {}; + } + var expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); + return expanded.map(function (t) { + return t.val; + }).join(""); + }; + DateTime.resetCache = function resetCache() { zoneOffsetTs = undefined; zoneOffsetGuessCache = {}; - } - - // INFO - - /** - * Get the value of unit. - * @param {string} unit - a unit such as 'minute' or 'day' - * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 - * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 - * @return {number} - */ - get(unit) { + }; + var _proto = DateTime.prototype; + _proto.get = function get(unit) { return this[unit]; - } - - /** - * Returns whether the DateTime is valid. Invalid DateTimes occur when: - * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 - * * The DateTime was created by an operation on another invalid date - * @type {boolean} - */ - get isValid() { - return this.invalid === null; - } - - /** - * Returns an error code if this DateTime is invalid, or null if the DateTime is valid - * @type {string} - */ - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - - /** - * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid - * @type {string} - */ - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - - /** - * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime - * - * @type {string} - */ - get locale() { - return this.isValid ? this.loc.locale : null; - } - - /** - * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime - * - * @type {string} - */ - get numberingSystem() { - return this.isValid ? this.loc.numberingSystem : null; - } - - /** - * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime - * - * @type {string} - */ - get outputCalendar() { - return this.isValid ? this.loc.outputCalendar : null; - } - - /** - * Get the time zone associated with this DateTime. - * @type {Zone} - */ - get zone() { - return this._zone; - } - - /** - * Get the name of the time zone. - * @type {string} - */ - get zoneName() { - return this.isValid ? this.zone.name : null; - } - - /** - * Get the year - * @example DateTime.local(2017, 5, 25).year //=> 2017 - * @type {number} - */ - get year() { - return this.isValid ? this.c.year : NaN; - } - - /** - * Get the quarter - * @example DateTime.local(2017, 5, 25).quarter //=> 2 - * @type {number} - */ - get quarter() { - return this.isValid ? Math.ceil(this.c.month / 3) : NaN; - } - - /** - * Get the month (1-12). - * @example DateTime.local(2017, 5, 25).month //=> 5 - * @type {number} - */ - get month() { - return this.isValid ? this.c.month : NaN; - } - - /** - * Get the day of the month (1-30ish). - * @example DateTime.local(2017, 5, 25).day //=> 25 - * @type {number} - */ - get day() { - return this.isValid ? this.c.day : NaN; - } - - /** - * Get the hour of the day (0-23). - * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 - * @type {number} - */ - get hour() { - return this.isValid ? this.c.hour : NaN; - } - - /** - * Get the minute of the hour (0-59). - * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 - * @type {number} - */ - get minute() { - return this.isValid ? this.c.minute : NaN; - } - - /** - * Get the second of the minute (0-59). - * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 - * @type {number} - */ - get second() { - return this.isValid ? this.c.second : NaN; - } - - /** - * Get the millisecond of the second (0-999). - * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 - * @type {number} - */ - get millisecond() { - return this.isValid ? this.c.millisecond : NaN; - } - - /** - * Get the week year - * @see https://en.wikipedia.org/wiki/ISO_week_date - * @example DateTime.local(2014, 12, 31).weekYear //=> 2015 - * @type {number} - */ - get weekYear() { - return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; - } - - /** - * Get the week number of the week year (1-52ish). - * @see https://en.wikipedia.org/wiki/ISO_week_date - * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 - * @type {number} - */ - get weekNumber() { - return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; - } - - /** - * Get the day of the week. - * 1 is Monday and 7 is Sunday - * @see https://en.wikipedia.org/wiki/ISO_week_date - * @example DateTime.local(2014, 11, 31).weekday //=> 4 - * @type {number} - */ - get weekday() { - return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; - } - - /** - * Returns true if this date is on a weekend according to the locale, false otherwise - * @returns {boolean} - */ - get isWeekend() { - return this.isValid && this.loc.getWeekendDays().includes(this.weekday); - } - - /** - * Get the day of the week according to the locale. - * 1 is the first day of the week and 7 is the last day of the week. - * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1, - * @returns {number} - */ - get localWeekday() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; - } - - /** - * Get the week number of the week year according to the locale. Different locales assign week numbers differently, - * because the week can start on different days of the week (see localWeekday) and because a different number of days - * is required for a week to count as the first week of a year. - * @returns {number} - */ - get localWeekNumber() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; - } - - /** - * Get the week year according to the locale. Different locales assign week numbers (and therefor week years) - * differently, see localWeekNumber. - * @returns {number} - */ - get localWeekYear() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN; - } - - /** - * Get the ordinal (meaning the day of the year) - * @example DateTime.local(2017, 5, 25).ordinal //=> 145 - * @type {number|DateTime} - */ - get ordinal() { - return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; - } - - /** - * Get the human readable short month name, such as 'Oct'. - * Defaults to the system's locale if no locale has been specified - * @example DateTime.local(2017, 10, 30).monthShort //=> Oct - * @type {string} - */ - get monthShort() { - return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null; - } - - /** - * Get the human readable long month name, such as 'October'. - * Defaults to the system's locale if no locale has been specified - * @example DateTime.local(2017, 10, 30).monthLong //=> October - * @type {string} - */ - get monthLong() { - return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null; - } - - /** - * Get the human readable short weekday, such as 'Mon'. - * Defaults to the system's locale if no locale has been specified - * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon - * @type {string} - */ - get weekdayShort() { - return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; - } - - /** - * Get the human readable long weekday, such as 'Monday'. - * Defaults to the system's locale if no locale has been specified - * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday - * @type {string} - */ - get weekdayLong() { - return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; - } - - /** - * Get the UTC offset of this DateTime in minutes - * @example DateTime.now().offset //=> -240 - * @example DateTime.utc().offset //=> 0 - * @type {number} - */ - get offset() { - return this.isValid ? +this.o : NaN; - } - - /** - * Get the short human name for the zone's current offset, for example "EST" or "EDT". - * Defaults to the system's locale if no locale has been specified - * @type {string} - */ - get offsetNameShort() { - if (this.isValid) { - return this.zone.offsetName(this.ts, { - format: "short", - locale: this.locale, - }); - } else { - return null; - } - } - - /** - * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". - * Defaults to the system's locale if no locale has been specified - * @type {string} - */ - get offsetNameLong() { - if (this.isValid) { - return this.zone.offsetName(this.ts, { - format: "long", - locale: this.locale, - }); - } else { - return null; - } - } - - /** - * Get whether this zone's offset ever changes, as in a DST. - * @type {boolean} - */ - get isOffsetFixed() { - return this.isValid ? this.zone.isUniversal : null; - } - - /** - * Get whether the DateTime is in a DST. - * @type {boolean} - */ - get isInDST() { - if (this.isOffsetFixed) { - return false; - } else { - return ( - this.offset > this.set({ month: 1, day: 1 }).offset || - this.offset > this.set({ month: 5 }).offset - ); - } - } - - /** - * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC - * in this DateTime's zone. During DST changes local time can be ambiguous, for example - * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`. - * This method will return both possible DateTimes if this DateTime's local time is ambiguous. - * @returns {DateTime[]} - */ - getPossibleOffsets() { + }; + _proto.getPossibleOffsets = function getPossibleOffsets() { if (!this.isValid || this.isOffsetFixed) { return [this]; } - const dayMs = 86400000; - const minuteMs = 60000; - const localTS = objToLocalTS(this.c); - const oEarlier = this.zone.offset(localTS - dayMs); - const oLater = this.zone.offset(localTS + dayMs); - - const o1 = this.zone.offset(localTS - oEarlier * minuteMs); - const o2 = this.zone.offset(localTS - oLater * minuteMs); + var dayMs = 86400000; + var minuteMs = 60000; + var localTS = objToLocalTS(this.c); + var oEarlier = this.zone.offset(localTS - dayMs); + var oLater = this.zone.offset(localTS + dayMs); + var o1 = this.zone.offset(localTS - oEarlier * minuteMs); + var o2 = this.zone.offset(localTS - oLater * minuteMs); if (o1 === o2) { return [this]; } - const ts1 = localTS - o1 * minuteMs; - const ts2 = localTS - o2 * minuteMs; - const c1 = tsToObj(ts1, o1); - const c2 = tsToObj(ts2, o2); - if ( - c1.hour === c2.hour && - c1.minute === c2.minute && - c1.second === c2.second && - c1.millisecond === c2.millisecond - ) { - return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })]; + var ts1 = localTS - o1 * minuteMs; + var ts2 = localTS - o2 * minuteMs; + var c1 = tsToObj(ts1, o1); + var c2 = tsToObj(ts2, o2); + if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { + return [clone(this, { + ts: ts1 + }), clone(this, { + ts: ts2 + })]; } return [this]; - } - - /** - * Returns true if this DateTime is in a leap year, false otherwise - * @example DateTime.local(2016).isInLeapYear //=> true - * @example DateTime.local(2013).isInLeapYear //=> false - * @type {boolean} - */ - get isInLeapYear() { - return isLeapYear(this.year); - } - - /** - * Returns the number of days in this DateTime's month - * @example DateTime.local(2016, 2).daysInMonth //=> 29 - * @example DateTime.local(2016, 3).daysInMonth //=> 31 - * @type {number} - */ - get daysInMonth() { - return daysInMonth(this.year, this.month); - } - - /** - * Returns the number of days in this DateTime's year - * @example DateTime.local(2016).daysInYear //=> 366 - * @example DateTime.local(2013).daysInYear //=> 365 - * @type {number} - */ - get daysInYear() { - return this.isValid ? daysInYear(this.year) : NaN; - } - - /** - * Returns the number of weeks in this DateTime's year - * @see https://en.wikipedia.org/wiki/ISO_week_date - * @example DateTime.local(2004).weeksInWeekYear //=> 53 - * @example DateTime.local(2013).weeksInWeekYear //=> 52 - * @type {number} - */ - get weeksInWeekYear() { - return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; - } - - /** - * Returns the number of weeks in this DateTime's local week year - * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52 - * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53 - * @type {number} - */ - get weeksInLocalWeekYear() { - return this.isValid - ? weeksInWeekYear( - this.localWeekYear, - this.loc.getMinDaysInFirstWeek(), - this.loc.getStartOfWeek() - ) - : NaN; - } - - /** - * Returns the resolved Intl options for this DateTime. - * This is useful in understanding the behavior of formatting methods - * @param {Object} opts - the same options as toLocaleString - * @return {Object} - */ - resolvedLocaleOptions(opts = {}) { - const { locale, numberingSystem, calendar } = Formatter.create( - this.loc.clone(opts), - opts - ).resolvedOptions(this); - return { locale, numberingSystem, outputCalendar: calendar }; - } - - // TRANSFORM - - /** - * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. - * - * Equivalent to {@link DateTime#setZone}('utc') - * @param {number} [offset=0] - optionally, an offset from UTC in minutes - * @param {Object} [opts={}] - options to pass to `setZone()` - * @return {DateTime} - */ - toUTC(offset = 0, opts = {}) { + }; + _proto.resolvedLocaleOptions = function resolvedLocaleOptions(opts) { + if (opts === void 0) { + opts = {}; + } + var _Formatter$create$res = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this), locale = _Formatter$create$res.locale, numberingSystem = _Formatter$create$res.numberingSystem, calendar = _Formatter$create$res.calendar; + return { + locale: locale, + numberingSystem: numberingSystem, + outputCalendar: calendar + }; + }; + _proto.toUTC = function toUTC(offset, opts) { + if (offset === void 0) { + offset = 0; + } + if (opts === void 0) { + opts = {}; + } return this.setZone(FixedOffsetZone.instance(offset), opts); - } - - /** - * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. - * - * Equivalent to `setZone('local')` - * @return {DateTime} - */ - toLocal() { + }; + _proto.toLocal = function toLocal() { return this.setZone(Settings.defaultZone); - } - - /** - * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. - * - * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones. - * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class. - * @param {Object} opts - options - * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. - * @return {DateTime} - */ - setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { + }; + _proto.setZone = function setZone(zone, _temp) { + var _ref2 = _temp === void 0 ? {} : _temp, _ref2$keepLocalTime = _ref2.keepLocalTime, keepLocalTime = _ref2$keepLocalTime === void 0 ? false : _ref2$keepLocalTime, _ref2$keepCalendarTim = _ref2.keepCalendarTime, keepCalendarTime = _ref2$keepCalendarTim === void 0 ? false : _ref2$keepCalendarTim; zone = normalizeZone(zone, Settings.defaultZone); if (zone.equals(this.zone)) { return this; } else if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } else { - let newTS = this.ts; + var newTS = this.ts; if (keepLocalTime || keepCalendarTime) { - const offsetGuess = zone.offset(this.ts); - const asObj = this.toObject(); - [newTS] = objToTS(asObj, offsetGuess, zone); + var offsetGuess = zone.offset(this.ts); + var asObj = this.toObject(); + var _objToTS3 = objToTS(asObj, offsetGuess, zone); + newTS = _objToTS3[0]; } - return clone(this, { ts: newTS, zone }); + return clone(this, { + ts: newTS, + zone: zone + }); } - } - - /** - * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. - * @param {Object} properties - the properties to set - * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) - * @return {DateTime} - */ - reconfigure({ locale, numberingSystem, outputCalendar } = {}) { - const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); - return clone(this, { loc }); - } - - /** - * "Set" the locale. Returns a newly-constructed DateTime. - * Just a convenient alias for reconfigure({ locale }) - * @example DateTime.local(2017, 5, 25).setLocale('en-GB') - * @return {DateTime} - */ - setLocale(locale) { - return this.reconfigure({ locale }); - } - - /** - * "Set" the values of specified units. Returns a newly-constructed DateTime. - * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. - * - * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`. - * They cannot be mixed with ISO-week units like `weekday`. - * @param {Object} values - a mapping of units to numbers - * @example dt.set({ year: 2017 }) - * @example dt.set({ hour: 8, minute: 30 }) - * @example dt.set({ weekday: 5 }) - * @example dt.set({ year: 2005, ordinal: 234 }) - * @return {DateTime} - */ - set(values) { + }; + _proto.reconfigure = function reconfigure(_temp2) { + var _ref3 = _temp2 === void 0 ? {} : _temp2, locale = _ref3.locale, numberingSystem = _ref3.numberingSystem, outputCalendar = _ref3.outputCalendar; + var loc = this.loc.clone({ + locale: locale, + numberingSystem: numberingSystem, + outputCalendar: outputCalendar + }); + return clone(this, { + loc: loc + }); + }; + _proto.setLocale = function setLocale(locale) { + return this.reconfigure({ + locale: locale + }); + }; + _proto.set = function set(values) { if (!this.isValid) return this; - - const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks); - const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc); - - const settingWeekStuff = - !isUndefined(normalized.weekYear) || - !isUndefined(normalized.weekNumber) || - !isUndefined(normalized.weekday), - containsOrdinal = !isUndefined(normalized.ordinal), - containsGregorYear = !isUndefined(normalized.year), - containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), - containsGregor = containsGregorYear || containsGregorMD, - definiteWeekDef = normalized.weekYear || normalized.weekNumber; - + var normalized = normalizeObject(values, normalizeUnitWithLocalWeeks); + var _usesLocalWeekValues2 = usesLocalWeekValues(normalized, this.loc), minDaysInFirstWeek = _usesLocalWeekValues2.minDaysInFirstWeek, startOfWeek = _usesLocalWeekValues2.startOfWeek; + var settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; if ((containsGregor || containsOrdinal) && definiteWeekDef) { - throw new ConflictingSpecificationError( - "Can't mix weekYear/weekNumber units with year/month/day or ordinals" - ); + throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } - if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } - - let mixed; + var mixed; if (settingWeekStuff) { - mixed = weekToGregorian( - { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized }, - minDaysInFirstWeek, - startOfWeek - ); + mixed = weekToGregorian(_extends({}, gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), normalized), minDaysInFirstWeek, startOfWeek); } else if (!isUndefined(normalized.ordinal)) { - mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized }); + mixed = ordinalToGregorian(_extends({}, gregorianToOrdinal(this.c), normalized)); } else { - mixed = { ...this.toObject(), ...normalized }; - - // if we didn't set the day but we ended up on an overflow date, - // use the last day of the right month + mixed = _extends({}, this.toObject(), normalized); if (isUndefined(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } - - const [ts, o] = objToTS(mixed, this.o, this.zone); - return clone(this, { ts, o }); - } - - /** - * Add a period of time to this DateTime and return the resulting DateTime - * - * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. - * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() - * @example DateTime.now().plus(123) //~> in 123 milliseconds - * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes - * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow - * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday - * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min - * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min - * @return {DateTime} - */ - plus(duration) { + var _objToTS4 = objToTS(mixed, this.o, this.zone), ts = _objToTS4[0], o = _objToTS4[1]; + return clone(this, { + ts: ts, + o: o + }); + }; + _proto.plus = function plus(duration) { if (!this.isValid) return this; - const dur = Duration.fromDurationLike(duration); + var dur = Duration.fromDurationLike(duration); return clone(this, adjustTime(this, dur)); - } - - /** - * Subtract a period of time to this DateTime and return the resulting DateTime - * See {@link DateTime#plus} - * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() - @return {DateTime} - */ - minus(duration) { + }; + _proto.minus = function minus(duration) { if (!this.isValid) return this; - const dur = Duration.fromDurationLike(duration).negate(); + var dur = Duration.fromDurationLike(duration).negate(); return clone(this, adjustTime(this, dur)); - } - - /** - * "Set" this DateTime to the beginning of a unit of time. - * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. - * @param {Object} opts - options - * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week - * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' - * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' - * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays - * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' - * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' - * @return {DateTime} - */ - startOf(unit, { useLocaleWeeks = false } = {}) { + }; + _proto.startOf = function startOf(unit, _temp3) { + var _ref4 = _temp3 === void 0 ? {} : _temp3, _ref4$useLocaleWeeks = _ref4.useLocaleWeeks, useLocaleWeeks = _ref4$useLocaleWeeks === void 0 ? false : _ref4$useLocaleWeeks; if (!this.isValid) return this; - - const o = {}, - normalizedUnit = Duration.normalizeUnit(unit); + var o = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case "years": o.month = 1; - // falls through case "quarters": case "months": o.day = 1; - // falls through case "weeks": case "days": o.hour = 0; - // falls through case "hours": o.minute = 0; - // falls through case "minutes": o.second = 0; - // falls through case "seconds": o.millisecond = 0; break; - // no default, invalid units throw in normalizeUnit() } - if (normalizedUnit === "weeks") { if (useLocaleWeeks) { - const startOfWeek = this.loc.getStartOfWeek(); - const { weekday } = this; + var startOfWeek = this.loc.getStartOfWeek(); + var weekday = this.weekday; if (weekday < startOfWeek) { o.weekNumber = this.weekNumber - 1; } @@ -7028,247 +4703,81 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; o.weekday = 1; } } - if (normalizedUnit === "quarters") { - const q = Math.ceil(this.month / 3); + var q = Math.ceil(this.month / 3); o.month = (q - 1) * 3 + 1; } - return this.set(o); - } - - /** - * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time - * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. - * @param {Object} opts - options - * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week - * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' - * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' - * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays - * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' - * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' - * @return {DateTime} - */ - endOf(unit, opts) { - return this.isValid - ? this.plus({ [unit]: 1 }) - .startOf(unit, opts) - .minus(1) - : this; - } - - // OUTPUT - - /** - * Returns a string representation of this DateTime formatted according to the specified format string. - * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). - * Defaults to en-US if no locale has been specified, regardless of the system's locale. - * @param {string} fmt - the format string - * @param {Object} opts - opts to override the configuration options on this DateTime - * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' - * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' - * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' - * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' - * @return {string} - */ - toFormat(fmt, opts = {}) { - return this.isValid - ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) - : INVALID; - } - - /** - * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. - * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation - * of the DateTime in the assigned locale. - * Defaults to the system's locale if no locale has been specified - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat - * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options - * @param {Object} opts - opts to override the configuration options on this DateTime - * @example DateTime.now().toLocaleString(); //=> 4/20/2017 - * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' - * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' - * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' - * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' - * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' - * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' - * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' - * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' - * @return {string} - */ - toLocaleString(formatOpts = DATE_SHORT, opts = {}) { - return this.isValid - ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) - : INVALID; - } - - /** - * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. - * Defaults to the system's locale if no locale has been specified - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts - * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. - * @example DateTime.now().toLocaleParts(); //=> [ - * //=> { type: 'day', value: '25' }, - * //=> { type: 'literal', value: '/' }, - * //=> { type: 'month', value: '05' }, - * //=> { type: 'literal', value: '/' }, - * //=> { type: 'year', value: '1982' } - * //=> ] - */ - toLocaleParts(opts = {}) { - return this.isValid - ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) - : []; - } - - /** - * Returns an ISO 8601-compliant string representation of this DateTime - * @param {Object} opts - options - * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 - * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 - * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' - * @param {boolean} [opts.extendedZone=false] - add the time zone format extension - * @param {string} [opts.format='extended'] - choose between the basic and extended format - * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' - * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' - * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' - * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' - * @return {string} - */ - toISO({ - format = "extended", - suppressSeconds = false, - suppressMilliseconds = false, - includeOffset = true, - extendedZone = false, - } = {}) { + }; + _proto.endOf = function endOf(unit, opts) { + var _this$plus; + return this.isValid ? this.plus((_this$plus = {}, _this$plus[unit] = 1, _this$plus)).startOf(unit, opts).minus(1) : this; + }; + _proto.toFormat = function toFormat(fmt, opts) { + if (opts === void 0) { + opts = {}; + } + return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; + }; + _proto.toLocaleString = function toLocaleString(formatOpts, opts) { + if (formatOpts === void 0) { + formatOpts = DATE_SHORT; + } + if (opts === void 0) { + opts = {}; + } + return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID; + }; + _proto.toLocaleParts = function toLocaleParts(opts) { + if (opts === void 0) { + opts = {}; + } + return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; + }; + _proto.toISO = function toISO(_temp4) { + var _ref5 = _temp4 === void 0 ? {} : _temp4, _ref5$format = _ref5.format, format = _ref5$format === void 0 ? "extended" : _ref5$format, _ref5$suppressSeconds = _ref5.suppressSeconds, suppressSeconds = _ref5$suppressSeconds === void 0 ? false : _ref5$suppressSeconds, _ref5$suppressMillise = _ref5.suppressMilliseconds, suppressMilliseconds = _ref5$suppressMillise === void 0 ? false : _ref5$suppressMillise, _ref5$includeOffset = _ref5.includeOffset, includeOffset = _ref5$includeOffset === void 0 ? true : _ref5$includeOffset, _ref5$extendedZone = _ref5.extendedZone, extendedZone = _ref5$extendedZone === void 0 ? false : _ref5$extendedZone; if (!this.isValid) { return null; } - - const ext = format === "extended"; - - let c = toISODate(this, ext); + var ext = format === "extended"; + var c = _toISODate(this, ext); c += "T"; - c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); + c += _toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); return c; - } - - /** - * Returns an ISO 8601-compliant string representation of this DateTime's date component - * @param {Object} opts - options - * @param {string} [opts.format='extended'] - choose between the basic and extended format - * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' - * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' - * @return {string} - */ - toISODate({ format = "extended" } = {}) { + }; + _proto.toISODate = function toISODate(_temp5) { + var _ref6 = _temp5 === void 0 ? {} : _temp5, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? "extended" : _ref6$format; if (!this.isValid) { return null; } - - return toISODate(this, format === "extended"); - } - - /** - * Returns an ISO 8601-compliant string representation of this DateTime's week date - * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' - * @return {string} - */ - toISOWeekDate() { + return _toISODate(this, format === "extended"); + }; + _proto.toISOWeekDate = function toISOWeekDate() { return toTechFormat(this, "kkkk-'W'WW-c"); - } - - /** - * Returns an ISO 8601-compliant string representation of this DateTime's time component - * @param {Object} opts - options - * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 - * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 - * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' - * @param {boolean} [opts.extendedZone=true] - add the time zone format extension - * @param {boolean} [opts.includePrefix=false] - include the `T` prefix - * @param {string} [opts.format='extended'] - choose between the basic and extended format - * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' - * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' - * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' - * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' - * @return {string} - */ - toISOTime({ - suppressMilliseconds = false, - suppressSeconds = false, - includeOffset = true, - includePrefix = false, - extendedZone = false, - format = "extended", - } = {}) { + }; + _proto.toISOTime = function toISOTime(_temp6) { + var _ref7 = _temp6 === void 0 ? {} : _temp6, _ref7$suppressMillise = _ref7.suppressMilliseconds, suppressMilliseconds = _ref7$suppressMillise === void 0 ? false : _ref7$suppressMillise, _ref7$suppressSeconds = _ref7.suppressSeconds, suppressSeconds = _ref7$suppressSeconds === void 0 ? false : _ref7$suppressSeconds, _ref7$includeOffset = _ref7.includeOffset, includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset, _ref7$includePrefix = _ref7.includePrefix, includePrefix = _ref7$includePrefix === void 0 ? false : _ref7$includePrefix, _ref7$extendedZone = _ref7.extendedZone, extendedZone = _ref7$extendedZone === void 0 ? false : _ref7$extendedZone, _ref7$format = _ref7.format, format = _ref7$format === void 0 ? "extended" : _ref7$format; if (!this.isValid) { return null; } - - let c = includePrefix ? "T" : ""; - return ( - c + - toISOTime( - this, - format === "extended", - suppressSeconds, - suppressMilliseconds, - includeOffset, - extendedZone - ) - ); - } - - /** - * Returns an RFC 2822-compatible string representation of this DateTime - * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' - * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' - * @return {string} - */ - toRFC2822() { + var c = includePrefix ? "T" : ""; + return c + _toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); + }; + _proto.toRFC2822 = function toRFC2822() { return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); - } - - /** - * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT. - * Specifically, the string conforms to RFC 1123. - * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 - * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' - * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' - * @return {string} - */ - toHTTP() { + }; + _proto.toHTTP = function toHTTP() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); - } - - /** - * Returns a string representation of this DateTime appropriate for use in SQL Date - * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' - * @return {string} - */ - toSQLDate() { + }; + _proto.toSQLDate = function toSQLDate() { if (!this.isValid) { return null; } - return toISODate(this, true); - } - - /** - * Returns a string representation of this DateTime appropriate for use in SQL Time - * @param {Object} opts - options - * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. - * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' - * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' - * @example DateTime.utc().toSQL() //=> '05:15:16.345' - * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' - * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' - * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' - * @return {string} - */ - toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { - let fmt = "HH:mm:ss.SSS"; - + return _toISODate(this, true); + }; + _proto.toSQLTime = function toSQLTime(_temp7) { + var _ref8 = _temp7 === void 0 ? {} : _temp7, _ref8$includeOffset = _ref8.includeOffset, includeOffset = _ref8$includeOffset === void 0 ? true : _ref8$includeOffset, _ref8$includeZone = _ref8.includeZone, includeZone = _ref8$includeZone === void 0 ? false : _ref8$includeZone, _ref8$includeOffsetSp = _ref8.includeOffsetSpace, includeOffsetSpace = _ref8$includeOffsetSp === void 0 ? true : _ref8$includeOffsetSp; + var fmt = "HH:mm:ss.SSS"; if (includeZone || includeOffset) { if (includeOffsetSpace) { fmt += " "; @@ -7279,578 +4788,540 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; fmt += "ZZ"; } } - return toTechFormat(this, fmt, true); - } - - /** - * Returns a string representation of this DateTime appropriate for use in SQL DateTime - * @param {Object} opts - options - * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. - * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' - * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' - * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' - * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' - * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' - * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' - * @return {string} - */ - toSQL(opts = {}) { + }; + _proto.toSQL = function toSQL(opts) { + if (opts === void 0) { + opts = {}; + } if (!this.isValid) { return null; } - - return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; - } - - /** - * Returns a string representation of this DateTime appropriate for debugging - * @return {string} - */ - toString() { + return this.toSQLDate() + " " + this.toSQLTime(opts); + }; + _proto.toString = function toString() { return this.isValid ? this.toISO() : INVALID; - } - - /** - * Returns a string representation of this DateTime appropriate for the REPL. - * @return {string} - */ - [Symbol.for("nodejs.util.inspect.custom")]() { + }; + _proto[_Symbol$for] = function () { if (this.isValid) { - return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`; + return "DateTime { ts: " + this.toISO() + ", zone: " + this.zone.name + ", locale: " + this.locale + " }"; } else { - return `DateTime { Invalid, reason: ${this.invalidReason} }`; + return "DateTime { Invalid, reason: " + this.invalidReason + " }"; } - } - - /** - * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis} - * @return {number} - */ - valueOf() { + }; + _proto.valueOf = function valueOf() { return this.toMillis(); - } - - /** - * Returns the epoch milliseconds of this DateTime. - * @return {number} - */ - toMillis() { + }; + _proto.toMillis = function toMillis() { return this.isValid ? this.ts : NaN; - } - - /** - * Returns the epoch seconds of this DateTime. - * @return {number} - */ - toSeconds() { + }; + _proto.toSeconds = function toSeconds() { return this.isValid ? this.ts / 1000 : NaN; - } - - /** - * Returns the epoch seconds (as a whole number) of this DateTime. - * @return {number} - */ - toUnixInteger() { + }; + _proto.toUnixInteger = function toUnixInteger() { return this.isValid ? Math.floor(this.ts / 1000) : NaN; - } - - /** - * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. - * @return {string} - */ - toJSON() { + }; + _proto.toJSON = function toJSON() { return this.toISO(); - } - - /** - * Returns a BSON serializable equivalent to this DateTime. - * @return {Date} - */ - toBSON() { + }; + _proto.toBSON = function toBSON() { return this.toJSDate(); - } - - /** - * Returns a JavaScript object with this DateTime's year, month, day, and so on. - * @param opts - options for generating the object - * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output - * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } - * @return {Object} - */ - toObject(opts = {}) { + }; + _proto.toObject = function toObject(opts) { + if (opts === void 0) { + opts = {}; + } if (!this.isValid) return {}; - - const base = { ...this.c }; - + var base = _extends({}, this.c); if (opts.includeConfig) { base.outputCalendar = this.outputCalendar; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; - } - - /** - * Returns a JavaScript Date equivalent to this DateTime. - * @return {Date} - */ - toJSDate() { + }; + _proto.toJSDate = function toJSDate() { return new Date(this.isValid ? this.ts : NaN); - } - - // COMPARE - - /** - * Return the difference between two DateTimes as a Duration. - * @param {DateTime} otherDateTime - the DateTime to compare this one to - * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. - * @param {Object} opts - options that affect the creation of the Duration - * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use - * @example - * var i1 = DateTime.fromISO('1982-05-25T09:45'), - * i2 = DateTime.fromISO('1983-10-14T10:30'); - * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } - * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } - * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } - * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } - * @return {Duration} - */ - diff(otherDateTime, unit = "milliseconds", opts = {}) { + }; + _proto.diff = function diff(otherDateTime, unit, opts) { + if (unit === void 0) { + unit = "milliseconds"; + } + if (opts === void 0) { + opts = {}; + } if (!this.isValid || !otherDateTime.isValid) { return Duration.invalid("created by diffing an invalid DateTime"); } - - const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts }; - - const units = maybeArray(unit).map(Duration.normalizeUnit), - otherIsLater = otherDateTime.valueOf() > this.valueOf(), - earlier = otherIsLater ? this : otherDateTime, - later = otherIsLater ? otherDateTime : this, - diffed = diff(earlier, later, units, durOpts); - + var durOpts = _extends({ + locale: this.locale, + numberingSystem: this.numberingSystem + }, opts); + var units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = _diff(earlier, later, units, durOpts); return otherIsLater ? diffed.negate() : diffed; - } - - /** - * Return the difference between this DateTime and right now. - * See {@link DateTime#diff} - * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration - * @param {Object} opts - options that affect the creation of the Duration - * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use - * @return {Duration} - */ - diffNow(unit = "milliseconds", opts = {}) { + }; + _proto.diffNow = function diffNow(unit, opts) { + if (unit === void 0) { + unit = "milliseconds"; + } + if (opts === void 0) { + opts = {}; + } return this.diff(DateTime.now(), unit, opts); - } - - /** - * Return an Interval spanning between this DateTime and another DateTime - * @param {DateTime} otherDateTime - the other end point of the Interval - * @return {Interval} - */ - until(otherDateTime) { + }; + _proto.until = function until(otherDateTime) { return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; - } - - /** - * Return whether this DateTime is in the same unit of time as another DateTime. - * Higher-order units must also be identical for this function to return `true`. - * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed. - * @param {DateTime} otherDateTime - the other DateTime - * @param {string} unit - the unit of time to check sameness on - * @param {Object} opts - options - * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used - * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day - * @return {boolean} - */ - hasSame(otherDateTime, unit, opts) { + }; + _proto.hasSame = function hasSame(otherDateTime, unit, opts) { if (!this.isValid) return false; - - const inputMs = otherDateTime.valueOf(); - const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); - return ( - adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts) - ); - } - - /** - * Equality check - * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid. - * To compare just the millisecond values, use `+dt1 === +dt2`. - * @param {DateTime} other - the other DateTime - * @return {boolean} - */ - equals(other) { - return ( - this.isValid && - other.isValid && - this.valueOf() === other.valueOf() && - this.zone.equals(other.zone) && - this.loc.equals(other.loc) - ); - } - - /** - * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your - * platform supports Intl.RelativeTimeFormat. Rounds down by default. - * @param {Object} options - options that affect the output - * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. - * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" - * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" - * @param {boolean} [options.round=true] - whether to round the numbers in the output. - * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. - * @param {string} options.locale - override the locale of this DateTime - * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this - * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" - * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" - * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" - * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" - * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" - * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" - */ - toRelative(options = {}) { + var inputMs = otherDateTime.valueOf(); + var adjustedToZone = this.setZone(otherDateTime.zone, { + keepLocalTime: true + }); + return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts); + }; + _proto.equals = function equals(other) { + return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); + }; + _proto.toRelative = function toRelative(options) { + if (options === void 0) { + options = {}; + } if (!this.isValid) return null; - const base = options.base || DateTime.fromObject({}, { zone: this.zone }), - padding = options.padding ? (this < base ? -options.padding : options.padding) : 0; - let units = ["years", "months", "days", "hours", "minutes", "seconds"]; - let unit = options.unit; + var base = options.base || DateTime.fromObject({}, { + zone: this.zone + }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; + var units = ["years", "months", "days", "hours", "minutes", "seconds"]; + var unit = options.unit; if (Array.isArray(options.unit)) { units = options.unit; unit = undefined; } - return diffRelative(base, this.plus(padding), { - ...options, + return diffRelative(base, this.plus(padding), _extends({}, options, { numeric: "always", - units, - unit, - }); - } - - /** - * Returns a string representation of this date relative to today, such as "yesterday" or "next month". - * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. - * @param {Object} options - options that affect the output - * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. - * @param {string} options.locale - override the locale of this DateTime - * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" - * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this - * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" - * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" - * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" - * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" - */ - toRelativeCalendar(options = {}) { + units: units, + unit: unit + })); + }; + _proto.toRelativeCalendar = function toRelativeCalendar(options) { + if (options === void 0) { + options = {}; + } if (!this.isValid) return null; - - return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, { - ...options, + return diffRelative(options.base || DateTime.fromObject({}, { + zone: this.zone + }), this, _extends({}, options, { numeric: "auto", units: ["years", "months", "days"], - calendary: true, - }); - } - - /** - * Return the min of several date times - * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum - * @return {DateTime} the min DateTime, or undefined if called with no argument - */ - static min(...dateTimes) { + calendary: true + })); + }; + DateTime.min = function min() { + for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { + dateTimes[_key] = arguments[_key]; + } if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("min requires all arguments be DateTimes"); } - return bestBy(dateTimes, (i) => i.valueOf(), Math.min); - } - - /** - * Return the max of several date times - * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum - * @return {DateTime} the max DateTime, or undefined if called with no argument - */ - static max(...dateTimes) { + return bestBy(dateTimes, function (i) { + return i.valueOf(); + }, Math.min); + }; + DateTime.max = function max() { + for (var _len2 = arguments.length, dateTimes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + dateTimes[_key2] = arguments[_key2]; + } if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } - return bestBy(dateTimes, (i) => i.valueOf(), Math.max); - } - - // MISC - - /** - * Explain how a string would be parsed by fromFormat() - * @param {string} text - the string to parse - * @param {string} fmt - the format the string is expected to be in (see description) - * @param {Object} options - options taken by fromFormat() - * @return {Object} - */ - static fromFormatExplain(text, fmt, options = {}) { - const { locale = null, numberingSystem = null } = options, - localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true, - }); + return bestBy(dateTimes, function (i) { + return i.valueOf(); + }, Math.max); + }; + DateTime.fromFormatExplain = function fromFormatExplain(text, fmt, options) { + if (options === void 0) { + options = {}; + } + var _options = options, _options$locale = _options.locale, locale = _options$locale === void 0 ? null : _options$locale, _options$numberingSys = _options.numberingSystem, numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys, localeToUse = Locale.fromOpts({ + locale: locale, + numberingSystem: numberingSystem, + defaultToEN: true + }); return explainFromTokens(localeToUse, text, fmt); - } - - /** - * @deprecated use fromFormatExplain instead - */ - static fromStringExplain(text, fmt, options = {}) { + }; + DateTime.fromStringExplain = function fromStringExplain(text, fmt, options) { + if (options === void 0) { + options = {}; + } return DateTime.fromFormatExplain(text, fmt, options); - } - - /** - * Build a parser for `fmt` using the given locale. This parser can be passed - * to {@link DateTime.fromFormatParser} to a parse a date in this format. This - * can be used to optimize cases where many dates need to be parsed in a - * specific format. - * - * @param {String} fmt - the format the string is expected to be in (see - * description) - * @param {Object} options - options used to set locale and numberingSystem - * for parser - * @returns {TokenParser} - opaque object to be used - */ - static buildFormatParser(fmt, options = {}) { - const { locale = null, numberingSystem = null } = options, - localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true, - }); + }; + DateTime.buildFormatParser = function buildFormatParser(fmt, options) { + if (options === void 0) { + options = {}; + } + var _options2 = options, _options2$locale = _options2.locale, locale = _options2$locale === void 0 ? null : _options2$locale, _options2$numberingSy = _options2.numberingSystem, numberingSystem = _options2$numberingSy === void 0 ? null : _options2$numberingSy, localeToUse = Locale.fromOpts({ + locale: locale, + numberingSystem: numberingSystem, + defaultToEN: true + }); return new TokenParser(localeToUse, fmt); - } - - /** - * Create a DateTime from an input string and format parser. - * - * The format parser must have been created with the same locale as this call. - * - * @param {String} text - the string to parse - * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser} - * @param {Object} opts - options taken by fromFormat() - * @returns {DateTime} - */ - static fromFormatParser(text, formatParser, opts = {}) { + }; + DateTime.fromFormatParser = function fromFormatParser(text, formatParser, opts) { + if (opts === void 0) { + opts = {}; + } if (isUndefined(text) || isUndefined(formatParser)) { - throw new InvalidArgumentError( - "fromFormatParser requires an input string and a format parser" - ); - } - const { locale = null, numberingSystem = null } = opts, - localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true, - }); - + throw new InvalidArgumentError("fromFormatParser requires an input string and a format parser"); + } + var _opts2 = opts, _opts2$locale = _opts2.locale, locale = _opts2$locale === void 0 ? null : _opts2$locale, _opts2$numberingSyste = _opts2.numberingSystem, numberingSystem = _opts2$numberingSyste === void 0 ? null : _opts2$numberingSyste, localeToUse = Locale.fromOpts({ + locale: locale, + numberingSystem: numberingSystem, + defaultToEN: true + }); if (!localeToUse.equals(formatParser.locale)) { - throw new InvalidArgumentError( - `fromFormatParser called with a locale of ${localeToUse}, ` + - `but the format parser was created for ${formatParser.locale}` - ); + throw new InvalidArgumentError("fromFormatParser called with a locale of " + localeToUse + ", " + ("but the format parser was created for " + formatParser.locale)); } - - const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text); - + var _formatParser$explain = formatParser.explainFromTokens(text), result = _formatParser$explain.result, zone = _formatParser$explain.zone, specificOffset = _formatParser$explain.specificOffset, invalidReason = _formatParser$explain.invalidReason; if (invalidReason) { return DateTime.invalid(invalidReason); } else { - return parseDataToDateTime( - result, - zone, - opts, - `format ${formatParser.format}`, - text, - specificOffset - ); + return parseDataToDateTime(result, zone, opts, "format " + formatParser.format, text, specificOffset); } - } - - // FORMAT PRESETS - - /** - * {@link DateTime#toLocaleString} format like 10/14/1983 - * @type {Object} - */ - static get DATE_SHORT() { - return DATE_SHORT; - } - - /** - * {@link DateTime#toLocaleString} format like 'Oct 14, 1983' - * @type {Object} - */ - static get DATE_MED() { - return DATE_MED; - } - - /** - * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983' - * @type {Object} - */ - static get DATE_MED_WITH_WEEKDAY() { - return DATE_MED_WITH_WEEKDAY; - } - - /** - * {@link DateTime#toLocaleString} format like 'October 14, 1983' - * @type {Object} - */ - static get DATE_FULL() { - return DATE_FULL; - } - - /** - * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983' - * @type {Object} - */ - static get DATE_HUGE() { - return DATE_HUGE; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get TIME_SIMPLE() { - return TIME_SIMPLE; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get TIME_WITH_SECONDS() { - return TIME_WITH_SECONDS; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. - * @type {Object} - */ - static get TIME_WITH_SHORT_OFFSET() { - return TIME_WITH_SHORT_OFFSET; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. - * @type {Object} - */ - static get TIME_WITH_LONG_OFFSET() { - return TIME_WITH_LONG_OFFSET; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30', always 24-hour. - * @type {Object} - */ - static get TIME_24_SIMPLE() { - return TIME_24_SIMPLE; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour. - * @type {Object} - */ - static get TIME_24_WITH_SECONDS() { - return TIME_24_WITH_SECONDS; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour. - * @type {Object} - */ - static get TIME_24_WITH_SHORT_OFFSET() { - return TIME_24_WITH_SHORT_OFFSET; - } - - /** - * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. - * @type {Object} - */ - static get TIME_24_WITH_LONG_OFFSET() { - return TIME_24_WITH_LONG_OFFSET; - } - - /** - * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_SHORT() { - return DATETIME_SHORT; - } - - /** - * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_SHORT_WITH_SECONDS() { - return DATETIME_SHORT_WITH_SECONDS; - } - - /** - * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_MED() { - return DATETIME_MED; - } - - /** - * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_MED_WITH_SECONDS() { - return DATETIME_MED_WITH_SECONDS; - } - - /** - * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_MED_WITH_WEEKDAY() { - return DATETIME_MED_WITH_WEEKDAY; - } - - /** - * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_FULL() { - return DATETIME_FULL; - } - - /** - * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_FULL_WITH_SECONDS() { - return DATETIME_FULL_WITH_SECONDS; - } - - /** - * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_HUGE() { - return DATETIME_HUGE; - } - - /** - * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. - * @type {Object} - */ - static get DATETIME_HUGE_WITH_SECONDS() { - return DATETIME_HUGE_WITH_SECONDS; - } - } - - /** - * @private - */ + }; + _createClass(DateTime, [{ + key: "isValid", + get: function get() { + return this.invalid === null; + } + }, { + key: "invalidReason", + get: function get() { + return this.invalid ? this.invalid.reason : null; + } + }, { + key: "invalidExplanation", + get: function get() { + return this.invalid ? this.invalid.explanation : null; + } + }, { + key: "locale", + get: function get() { + return this.isValid ? this.loc.locale : null; + } + }, { + key: "numberingSystem", + get: function get() { + return this.isValid ? this.loc.numberingSystem : null; + } + }, { + key: "outputCalendar", + get: function get() { + return this.isValid ? this.loc.outputCalendar : null; + } + }, { + key: "zone", + get: function get() { + return this._zone; + } + }, { + key: "zoneName", + get: function get() { + return this.isValid ? this.zone.name : null; + } + }, { + key: "year", + get: function get() { + return this.isValid ? this.c.year : NaN; + } + }, { + key: "quarter", + get: function get() { + return this.isValid ? Math.ceil(this.c.month / 3) : NaN; + } + }, { + key: "month", + get: function get() { + return this.isValid ? this.c.month : NaN; + } + }, { + key: "day", + get: function get() { + return this.isValid ? this.c.day : NaN; + } + }, { + key: "hour", + get: function get() { + return this.isValid ? this.c.hour : NaN; + } + }, { + key: "minute", + get: function get() { + return this.isValid ? this.c.minute : NaN; + } + }, { + key: "second", + get: function get() { + return this.isValid ? this.c.second : NaN; + } + }, { + key: "millisecond", + get: function get() { + return this.isValid ? this.c.millisecond : NaN; + } + }, { + key: "weekYear", + get: function get() { + return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; + } + }, { + key: "weekNumber", + get: function get() { + return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; + } + }, { + key: "weekday", + get: function get() { + return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; + } + }, { + key: "isWeekend", + get: function get() { + return this.isValid && this.loc.getWeekendDays().includes(this.weekday); + } + }, { + key: "localWeekday", + get: function get() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; + } + }, { + key: "localWeekNumber", + get: function get() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; + } + }, { + key: "localWeekYear", + get: function get() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN; + } + }, { + key: "ordinal", + get: function get() { + return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; + } + }, { + key: "monthShort", + get: function get() { + return this.isValid ? Info.months("short", { + locObj: this.loc + })[this.month - 1] : null; + } + }, { + key: "monthLong", + get: function get() { + return this.isValid ? Info.months("long", { + locObj: this.loc + })[this.month - 1] : null; + } + }, { + key: "weekdayShort", + get: function get() { + return this.isValid ? Info.weekdays("short", { + locObj: this.loc + })[this.weekday - 1] : null; + } + }, { + key: "weekdayLong", + get: function get() { + return this.isValid ? Info.weekdays("long", { + locObj: this.loc + })[this.weekday - 1] : null; + } + }, { + key: "offset", + get: function get() { + return this.isValid ? +this.o : NaN; + } + }, { + key: "offsetNameShort", + get: function get() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "short", + locale: this.locale + }); + } else { + return null; + } + } + }, { + key: "offsetNameLong", + get: function get() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "long", + locale: this.locale + }); + } else { + return null; + } + } + }, { + key: "isOffsetFixed", + get: function get() { + return this.isValid ? this.zone.isUniversal : null; + } + }, { + key: "isInDST", + get: function get() { + if (this.isOffsetFixed) { + return false; + } else { + return this.offset > this.set({ + month: 1, + day: 1 + }).offset || this.offset > this.set({ + month: 5 + }).offset; + } + } + }, { + key: "isInLeapYear", + get: function get() { + return isLeapYear(this.year); + } + }, { + key: "daysInMonth", + get: function get() { + return daysInMonth(this.year, this.month); + } + }, { + key: "daysInYear", + get: function get() { + return this.isValid ? daysInYear(this.year) : NaN; + } + }, { + key: "weeksInWeekYear", + get: function get() { + return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; + } + }, { + key: "weeksInLocalWeekYear", + get: function get() { + return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN; + } + }], [{ + key: "DATE_SHORT", + get: function get() { + return DATE_SHORT; + } + }, { + key: "DATE_MED", + get: function get() { + return DATE_MED; + } + }, { + key: "DATE_MED_WITH_WEEKDAY", + get: function get() { + return DATE_MED_WITH_WEEKDAY; + } + }, { + key: "DATE_FULL", + get: function get() { + return DATE_FULL; + } + }, { + key: "DATE_HUGE", + get: function get() { + return DATE_HUGE; + } + }, { + key: "TIME_SIMPLE", + get: function get() { + return TIME_SIMPLE; + } + }, { + key: "TIME_WITH_SECONDS", + get: function get() { + return TIME_WITH_SECONDS; + } + }, { + key: "TIME_WITH_SHORT_OFFSET", + get: function get() { + return TIME_WITH_SHORT_OFFSET; + } + }, { + key: "TIME_WITH_LONG_OFFSET", + get: function get() { + return TIME_WITH_LONG_OFFSET; + } + }, { + key: "TIME_24_SIMPLE", + get: function get() { + return TIME_24_SIMPLE; + } + }, { + key: "TIME_24_WITH_SECONDS", + get: function get() { + return TIME_24_WITH_SECONDS; + } + }, { + key: "TIME_24_WITH_SHORT_OFFSET", + get: function get() { + return TIME_24_WITH_SHORT_OFFSET; + } + }, { + key: "TIME_24_WITH_LONG_OFFSET", + get: function get() { + return TIME_24_WITH_LONG_OFFSET; + } + }, { + key: "DATETIME_SHORT", + get: function get() { + return DATETIME_SHORT; + } + }, { + key: "DATETIME_SHORT_WITH_SECONDS", + get: function get() { + return DATETIME_SHORT_WITH_SECONDS; + } + }, { + key: "DATETIME_MED", + get: function get() { + return DATETIME_MED; + } + }, { + key: "DATETIME_MED_WITH_SECONDS", + get: function get() { + return DATETIME_MED_WITH_SECONDS; + } + }, { + key: "DATETIME_MED_WITH_WEEKDAY", + get: function get() { + return DATETIME_MED_WITH_WEEKDAY; + } + }, { + key: "DATETIME_FULL", + get: function get() { + return DATETIME_FULL; + } + }, { + key: "DATETIME_FULL_WITH_SECONDS", + get: function get() { + return DATETIME_FULL_WITH_SECONDS; + } + }, { + key: "DATETIME_HUGE", + get: function get() { + return DATETIME_HUGE; + } + }, { + key: "DATETIME_HUGE_WITH_SECONDS", + get: function get() { + return DATETIME_HUGE_WITH_SECONDS; + } + }]); + return DateTime; + })(Symbol.for("nodejs.util.inspect.custom")); function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; @@ -7859,27 +5330,37 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else if (dateTimeish && typeof dateTimeish === "object") { return DateTime.fromObject(dateTimeish); } else { - throw new InvalidArgumentError( - `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}` - ); - } - } - - const VERSION = "3.5.0"; - - const __esModule = true; - - exports.DateTime = DateTime; - exports.Duration = Duration; - exports.FixedOffsetZone = FixedOffsetZone; - exports.IANAZone = IANAZone; - exports.Info = Info; - exports.Interval = Interval; - exports.InvalidZone = InvalidZone; - exports.Settings = Settings; - exports.SystemZone = SystemZone; - exports.VERSION = VERSION; - exports.Zone = Zone; - exports.__esModule = __esModule; + throw new InvalidArgumentError("Unknown datetime argument: " + dateTimeish + ", of type " + typeof dateTimeish); + } + } + var VERSION = "3.5.0"; + var DateTime_1 = luxon.DateTime = DateTime; + var Duration_1 = luxon.Duration = Duration; + var FixedOffsetZone_1 = luxon.FixedOffsetZone = FixedOffsetZone; + var IANAZone_1 = luxon.IANAZone = IANAZone; + var Info_1 = luxon.Info = Info; + var Interval_1 = luxon.Interval = Interval; + var InvalidZone_1 = luxon.InvalidZone = InvalidZone; + var Settings_1 = luxon.Settings = Settings; + var SystemZone_1 = luxon.SystemZone = SystemZone; + var VERSION_1 = luxon.VERSION = VERSION; + var Zone_1 = luxon.Zone = Zone; + + let exp = luxon?.default || luxon || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} + + exports.DateTime = DateTime_1; + exports.Duration = Duration_1; + exports.FixedOffsetZone = FixedOffsetZone_1; + exports.IANAZone = IANAZone_1; + exports.Info = Info_1; + exports.Interval = Interval_1; + exports.InvalidZone = InvalidZone_1; + exports.Settings = Settings_1; + exports.SystemZone = SystemZone_1; + exports.VERSION = VERSION_1; + exports.Zone = Zone_1; + exports.default = exp; + + Object.defineProperty(exports, '__esModule', { value: true }); })); diff --git a/packages/ui5-tooling-modules/test/__snap__/3a92fee2/@ui5/webcomponents/dist/CheckBox.js b/packages/ui5-tooling-modules/test/__snap__/3a92fee2/@ui5/webcomponents/dist/CheckBox.js index 8c95be70..6d307180 100644 --- a/packages/ui5-tooling-modules/test/__snap__/3a92fee2/@ui5/webcomponents/dist/CheckBox.js +++ b/packages/ui5-tooling-modules/test/__snap__/3a92fee2/@ui5/webcomponents/dist/CheckBox.js @@ -1,3926 +1,240 @@ sap.ui.define((function () { 'use strict'; - const isSSR$3 = typeof document === "undefined"; - const internals$1 = { - get userAgent() { - if (isSSR$3) { - return ""; - } - return navigator.userAgent; - }, - get touch() { - if (isSSR$3) { - return false; - } - return "ontouchstart" in window || navigator.maxTouchPoints > 0; - }, - get chrome() { - if (isSSR$3) { - return false; - } - return /(Chrome|CriOS)/.test(internals$1.userAgent); - }, - get firefox() { - if (isSSR$3) { - return false; - } - return /Firefox/.test(internals$1.userAgent); - }, - get safari() { - if (isSSR$3) { - return false; - } - return !internals$1.chrome && /(Version|PhantomJS)\/(\d+\.\d+).*Safari/.test(internals$1.userAgent); - }, - get webkit() { - if (isSSR$3) { - return false; - } - return /webkit/.test(internals$1.userAgent); - }, - get windows() { - if (isSSR$3) { - return false; - } - return navigator.platform.indexOf("Win") !== -1; - }, - get macOS() { - if (isSSR$3) { - return false; - } - return !!navigator.userAgent.match(/Macintosh|Mac OS X/i); - }, - get iOS() { - if (isSSR$3) { - return false; - } - return !!(navigator.platform.match(/iPhone|iPad|iPod/)) || !!(internals$1.userAgent.match(/Mac/) && "ontouchend" in document); - }, - get android() { - if (isSSR$3) { - return false; - } - return !internals$1.windows && /Android/.test(internals$1.userAgent); - }, - get androidPhone() { - if (isSSR$3) { - return false; - } - return internals$1.android && /(?=android)(?=.*mobile)/i.test(internals$1.userAgent); - }, - get ipad() { - if (isSSR$3) { - return false; - } - // With iOS 13 the string 'iPad' was removed from the user agent string through a browser setting, which is applied on all sites by default: - // "Request Desktop Website -> All websites" (for more infos see: https://forums.developer.apple.com/thread/119186). - // Therefore the OS is detected as MACINTOSH instead of iOS and the device is a tablet if the Device.support.touch is true. - return /ipad/i.test(internals$1.userAgent) || (/Macintosh/i.test(internals$1.userAgent) && "ontouchend" in document); - }, - _isPhone() { - detectTablet(); - return internals$1.touch && !tablet; - }, - }; - let windowsVersion; - let webkitVersion; - let tablet; - const isWindows8OrAbove = () => { - if (isSSR$3) { - return false; - } - if (!internals$1.windows) { - return false; - } - if (windowsVersion === undefined) { - const matches = internals$1.userAgent.match(/Windows NT (\d+).(\d)/); - windowsVersion = matches ? parseFloat(matches[1]) : 0; - } - return windowsVersion >= 8; - }; - const isWebkit537OrAbove = () => { - if (isSSR$3) { - return false; - } - if (!internals$1.webkit) { - return false; - } - if (webkitVersion === undefined) { - const matches = internals$1.userAgent.match(/(webkit)[ /]([\w.]+)/); - webkitVersion = matches ? parseFloat(matches[1]) : 0; - } - return webkitVersion >= 537.10; - }; - const detectTablet = () => { - if (isSSR$3) { - return false; - } - if (tablet !== undefined) { - return; - } - if (internals$1.ipad) { - tablet = true; - return; - } - if (internals$1.touch) { - if (isWindows8OrAbove()) { - tablet = true; - return; - } - if (internals$1.chrome && internals$1.android) { - tablet = !/Mobile Safari\/[.0-9]+/.test(internals$1.userAgent); - return; - } - let densityFactor = window.devicePixelRatio ? window.devicePixelRatio : 1; // may be undefined in Windows Phone devices - if (internals$1.android && isWebkit537OrAbove()) { - densityFactor = 1; - } - tablet = (Math.min(window.screen.width / densityFactor, window.screen.height / densityFactor) >= 600); - return; - } - tablet = internals$1.userAgent.indexOf("Touch") !== -1 || (internals$1.android && !internals$1.androidPhone); - }; - const isSafari = () => internals$1.safari; - const isTablet = () => { - detectTablet(); - return (internals$1.touch || isWindows8OrAbove()) && tablet; - }; - const isPhone = () => { - return internals$1._isPhone(); - }; - const isDesktop = () => { - if (isSSR$3) { - return false; - } - return (!isTablet() && !isPhone()) || isWindows8OrAbove(); - }; - const isIOS = () => { - return internals$1.iOS; - }; - - var class2type = {}; - var hasOwn = class2type.hasOwnProperty; - var toString = class2type.toString; - var fnToString = hasOwn.toString; - var ObjectFunctionString = fnToString.call(Object); - var fnIsPlainObject = function (obj) { - var proto, Ctor; - if (!obj || toString.call(obj) !== "[object Object]") { - return false; - } - proto = Object.getPrototypeOf(obj); - if (!proto) { - return true; - } - Ctor = hasOwn.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString; - }; - - var oToken = Object.create(null); - var fnMerge$1 = function (arg1, arg2, arg3, arg4) { - var src, copyIsArray, copy, name, options, clone, target = arguments[2] || {}, i = 3, length = arguments.length, deep = arguments[0] || false, skipToken = arguments[1] ? undefined : oToken; - if (typeof target !== 'object' && typeof target !== 'function') { - target = {}; - } - for (; i < length; i++) { - if ((options = arguments[i]) != null) { - for (name in options) { - src = target[name]; - copy = options[name]; - if (name === '__proto__' || target === copy) { - continue; - } - if (deep && copy && (fnIsPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && Array.isArray(src) ? src : []; - } - else { - clone = src && fnIsPlainObject(src) ? src : {}; - } - target[name] = fnMerge$1(deep, arguments[1], clone, copy); - } - else if (copy !== skipToken) { - target[name] = copy; - } - } - } - } - return target; - }; - - const fnMerge = function (arg1, arg2) { - return fnMerge$1(true, false, ...arguments); - }; - - const whenDOMReady = () => { - return new Promise(resolve => { - if (document.body) { - resolve(); - } - else { - document.addEventListener("DOMContentLoaded", () => { - resolve(); - }); - } - }); - }; - - class EventProvider { - constructor() { - this._eventRegistry = new Map(); - } - attachEvent(eventName, fnFunction) { - const eventRegistry = this._eventRegistry; - const eventListeners = eventRegistry.get(eventName); - if (!Array.isArray(eventListeners)) { - eventRegistry.set(eventName, [fnFunction]); - return; - } - if (!eventListeners.includes(fnFunction)) { - eventListeners.push(fnFunction); - } - } - detachEvent(eventName, fnFunction) { - const eventRegistry = this._eventRegistry; - const eventListeners = eventRegistry.get(eventName); - if (!eventListeners) { - return; - } - const indexOfFnToDetach = eventListeners.indexOf(fnFunction); - if (indexOfFnToDetach !== -1) { - eventListeners.splice(indexOfFnToDetach, 1); - } - if (eventListeners.length === 0) { - eventRegistry.delete(eventName); - } - } - /** - * Fires an event and returns the results of all event listeners as an array. - * - * @param eventName the event to fire - * @param data optional data to pass to each event listener - * @returns {Array} an array with the results of all event listeners - */ - fireEvent(eventName, data) { - const eventRegistry = this._eventRegistry; - const eventListeners = eventRegistry.get(eventName); - if (!eventListeners) { - return []; - } - return eventListeners.map(fn => { - return fn.call(this, data); - }); - } - /** - * Fires an event and returns a promise that will resolve once all listeners have resolved. - * - * @param eventName the event to fire - * @param data optional data to pass to each event listener - * @returns {Promise} a promise that will resolve when all listeners have resolved - */ - fireEventAsync(eventName, data) { - return Promise.all(this.fireEvent(eventName, data)); - } - isHandlerAttached(eventName, fnFunction) { - const eventRegistry = this._eventRegistry; - const eventListeners = eventRegistry.get(eventName); - if (!eventListeners) { - return false; - } - return eventListeners.includes(fnFunction); - } - hasListeners(eventName) { - return !!this._eventRegistry.get(eventName); - } - } - - /** - * Returns a singleton HTML element, inserted in given parent element of HTML page, - * used mostly to store and share global resources between multiple UI5 Web Components runtimes. - * - * @param { string } tag the element tag/selector - * @param { HTMLElement } parentElement the parent element to insert the singleton element instance - * @param { Function } createEl a factory function for the element instantiation, by default document.createElement is used - * @returns { Element } - */ - const getSingletonElementInstance = (tag, parentElement = document.body, createEl) => { - let el = document.querySelector(tag); - if (el) { - return el; - } - el = createEl ? createEl() : document.createElement(tag); - return parentElement.insertBefore(el, parentElement.firstChild); - }; - - const getMetaDomEl = () => { - const el = document.createElement("meta"); - el.setAttribute("name", "ui5-shared-resources"); - el.setAttribute("content", ""); // attribute "content" should be present when "name" is set. - return el; - }; - const getSharedResourcesInstance = () => { - if (typeof document === "undefined") { - return null; - } - return getSingletonElementInstance(`meta[name="ui5-shared-resources"]`, document.head, getMetaDomEl); - }; - /** - * Use this method to initialize/get resources that you would like to be shared among UI5 Web Components runtime instances. - * The data will be accessed via a singleton "ui5-shared-resources" HTML element in the "body" element of the page. - * - * @public - * @param namespace Unique ID of the resource, may contain "." to denote hierarchy - * @param initialValue Object or primitive that will be used as an initial value if the resource does not exist - * @returns {*} - */ - const getSharedResource = (namespace, initialValue) => { - const parts = namespace.split("."); - let current = getSharedResourcesInstance(); - if (!current) { - return initialValue; - } - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - const lastPart = i === parts.length - 1; - if (!Object.prototype.hasOwnProperty.call(current, part)) { - current[part] = lastPart ? initialValue : {}; - } - current = current[part]; - } - return current; - }; - - const Tags = getSharedResource("Tags", new Map()); - const Definitions = new Set(); - let Failures = new Map(); - let failureTimeout; - const UNKNOWN_RUNTIME = -1; - const registerTag = tag => { - Definitions.add(tag); - Tags.set(tag, getCurrentRuntimeIndex()); - }; - const isTagRegistered = tag => { - return Definitions.has(tag); - }; - const getAllRegisteredTags = () => { - return [...Definitions.values()]; - }; - const recordTagRegistrationFailure = tag => { - let tagRegRuntimeIndex = Tags.get(tag); - if (tagRegRuntimeIndex === undefined) { - tagRegRuntimeIndex = UNKNOWN_RUNTIME; - } - if (!Failures.has(tagRegRuntimeIndex)) { - Failures.set(tagRegRuntimeIndex, new Set()); - } - Failures.get(tagRegRuntimeIndex).add(tag); - if (!failureTimeout) { - failureTimeout = setTimeout(() => { - displayFailedRegistrations(); - Failures = new Map(); - failureTimeout = undefined; - }, 1000); - } - }; - const displayFailedRegistrations = () => { - const allRuntimes = getAllRuntimes(); - const currentRuntimeIndex = getCurrentRuntimeIndex(); - const currentRuntime = allRuntimes[currentRuntimeIndex]; - let message = `Multiple UI5 Web Components instances detected.`; - if (allRuntimes.length > 1) { - message = `${message}\nLoading order (versions before 1.1.0 not listed): ${allRuntimes.map(runtime => `\n${runtime.description}`).join("")}`; - } - [...Failures.keys()].forEach(otherRuntimeIndex => { - let comparison; - let otherRuntime; - if (otherRuntimeIndex === UNKNOWN_RUNTIME) { - comparison = 1; - otherRuntime = { - description: `Older unknown runtime` - }; - } else { - comparison = compareRuntimes(currentRuntimeIndex, otherRuntimeIndex); - otherRuntime = allRuntimes[otherRuntimeIndex]; - } - let compareWord; - if (comparison > 0) { - compareWord = "an older"; - } else if (comparison < 0) { - compareWord = "a newer"; - } else { - compareWord = "the same"; - } - message = `${message}\n\n"${currentRuntime.description}" failed to define ${Failures.get(otherRuntimeIndex).size} tag(s) as they were defined by a runtime of ${compareWord} version "${otherRuntime.description}": ${[...Failures.get(otherRuntimeIndex)].sort().join(", ")}.`; - if (comparison > 0) { - message = `${message}\nWARNING! If your code uses features of the above web components, unavailable in ${otherRuntime.description}, it might not work as expected!`; - } else { - message = `${message}\nSince the above web components were defined by the same or newer version runtime, they should be compatible with your code.`; - } - }); - message = `${message}\n\nTo prevent other runtimes from defining tags that you use, consider using scoping or have third-party libraries use scoping: https://github.com/SAP/ui5-webcomponents/blob/main/docs/2-advanced/03-scoping.md.`; - console.warn(message); - }; - - const VersionInfo = { - version: "2.5.0", - major: 2, - minor: 5, - patch: 0, - suffix: "", - isNext: false, - buildTime: 1733409507, - }; - - let suf; - let rulesObj = { - include: [/^ui5-/], - exclude: [], - }; - const tagsCache = new Map(); // true/false means the tag should/should not be cached, undefined means not known yet. - /** - * Returns the currently set scoping suffix, or undefined if not set. - * - * @public - * @returns {String|undefined} - */ - const getCustomElementsScopingSuffix = () => { - return suf; - }; - /** - * Returns the rules, governing which custom element tags to scope and which not. By default, all elements - * starting with "ui5-" are scoped. The default rules are: {include: [/^ui5-/]}. - * - * @public - * @returns {Object} - */ - const getCustomElementsScopingRules = () => { - return rulesObj; - }; - /** - * Determines whether custom elements with the given tag should be scoped or not. - * The tag is first matched against the "include" rules and then against the "exclude" rules and the - * result is cached until new rules are set. - * - * @public - * @param tag - */ - const shouldScopeCustomElement = (tag) => { - if (!tagsCache.has(tag)) { - const result = rulesObj.include.some(rule => tag.match(rule)) && !rulesObj.exclude.some(rule => tag.match(rule)); - tagsCache.set(tag, result); - } - return tagsCache.get(tag); - }; - /** - * Returns the currently set scoping suffix, if any and if the tag should be scoped, or undefined otherwise. - * - * @public - * @param tag - * @returns {String} - */ - const getEffectiveScopingSuffixForTag = (tag) => { - if (shouldScopeCustomElement(tag)) { - return getCustomElementsScopingSuffix(); - } - }; - - let currentRuntimeIndex; - let currentRuntimeAlias = ""; - const compareCache = new Map(); - /** - * Central registry where all runtimes register themselves by pushing an object. - * The index in the registry servers as an ID for the runtime. - * @type {*} - */ - const Runtimes = getSharedResource("Runtimes", []); - /** - * Registers the current runtime in the shared runtimes resource registry - */ - const registerCurrentRuntime = () => { - if (currentRuntimeIndex === undefined) { - currentRuntimeIndex = Runtimes.length; - const versionInfo = VersionInfo; - Runtimes.push({ - ...versionInfo, - get scopingSuffix() { - return getCustomElementsScopingSuffix(); - }, - get registeredTags() { - return getAllRegisteredTags(); - }, - get scopingRules() { - return getCustomElementsScopingRules(); - }, - alias: currentRuntimeAlias, - description: `Runtime ${currentRuntimeIndex} - ver ${versionInfo.version}${""}`, - }); - } - }; - /** - * Returns the index of the current runtime's object in the shared runtimes resource registry - * @returns {*} - */ - const getCurrentRuntimeIndex = () => { - return currentRuntimeIndex; - }; - /** - * Compares two runtimes and returns 1 if the first is of a bigger version, -1 if the second is of a bigger version, and 0 if equal - * @param index1 The index of the first runtime to compare - * @param index2 The index of the second runtime to compare - * @returns {number} - */ - const compareRuntimes = (index1, index2) => { - const cacheIndex = `${index1},${index2}`; - if (compareCache.has(cacheIndex)) { - return compareCache.get(cacheIndex); - } - const runtime1 = Runtimes[index1]; - const runtime2 = Runtimes[index2]; - if (!runtime1 || !runtime2) { - throw new Error("Invalid runtime index supplied"); - } - // If any of the two is a next version, bigger buildTime wins - if (runtime1.isNext || runtime2.isNext) { - return runtime1.buildTime - runtime2.buildTime; - } - // If major versions differ, bigger one wins - const majorDiff = runtime1.major - runtime2.major; - if (majorDiff) { - return majorDiff; - } - // If minor versions differ, bigger one wins - const minorDiff = runtime1.minor - runtime2.minor; - if (minorDiff) { - return minorDiff; - } - // If patch versions differ, bigger one wins - const patchDiff = runtime1.patch - runtime2.patch; - if (patchDiff) { - return patchDiff; - } - // Bigger suffix wins, f.e. rc10 > rc9 - // Important: suffix is alphanumeric, must use natural compare - const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }); - const result = collator.compare(runtime1.suffix, runtime2.suffix); - compareCache.set(cacheIndex, result); - return result; - }; - const getAllRuntimes = () => { - return Runtimes; - }; - - const isSSR$2 = typeof document === "undefined"; - const getStyleId = (name, value) => { - return value ? `${name}|${value}` : name; - }; - const shouldUpdate = (runtimeIndex) => { - if (runtimeIndex === undefined) { - return true; - } - return compareRuntimes(getCurrentRuntimeIndex(), parseInt(runtimeIndex)) === 1; // 1 means the current is newer, 0 means the same, -1 means the resource's runtime is newer - }; - const createStyle = (data, name, value = "", theme) => { - const content = typeof data === "string" ? data : data.content; - const currentRuntimeIndex = getCurrentRuntimeIndex(); - const stylesheet = new CSSStyleSheet(); - stylesheet.replaceSync(content); - stylesheet._ui5StyleId = getStyleId(name, value); // set an id so that we can find the style later - if (theme) { - stylesheet._ui5RuntimeIndex = currentRuntimeIndex; - stylesheet._ui5Theme = theme; - } - document.adoptedStyleSheets = [...document.adoptedStyleSheets, stylesheet]; - }; - const updateStyle = (data, name, value = "", theme) => { - const content = typeof data === "string" ? data : data.content; - const currentRuntimeIndex = getCurrentRuntimeIndex(); - const stylesheet = document.adoptedStyleSheets.find(sh => sh._ui5StyleId === getStyleId(name, value)); - if (!stylesheet) { - return; - } - if (!theme) { - stylesheet.replaceSync(content || ""); - } - else { - const stylesheetRuntimeIndex = stylesheet._ui5RuntimeIndex; - const stylesheetTheme = stylesheet._ui5Theme; - if (stylesheetTheme !== theme || shouldUpdate(stylesheetRuntimeIndex)) { - stylesheet.replaceSync(content || ""); - stylesheet._ui5RuntimeIndex = String(currentRuntimeIndex); - stylesheet._ui5Theme = theme; - } - } - }; - const hasStyle = (name, value = "") => { - if (isSSR$2) { - return true; - } - return !!document.adoptedStyleSheets.find(sh => sh._ui5StyleId === getStyleId(name, value)); - }; - const removeStyle = (name, value = "") => { - document.adoptedStyleSheets = document.adoptedStyleSheets.filter(sh => sh._ui5StyleId !== getStyleId(name, value)); - }; - const createOrUpdateStyle = (data, name, value = "", theme) => { - if (hasStyle(name, value)) { - updateStyle(data, name, value, theme); - } - else { - createStyle(data, name, value, theme); - } - }; - const mergeStyles = (style1, style2) => { - if (style1 === undefined) { - return style2; - } - if (style2 === undefined) { - return style1; - } - const style2Content = typeof style2 === "string" ? style2 : style2.content; - if (typeof style1 === "string") { - return `${style1} ${style2Content}`; - } - return { - content: `${style1.content} ${style2Content}`, - packageName: style1.packageName, - fileName: style1.fileName, - }; - }; - - const features = new Map(); - const componentFeatures = new Map(); - const subscribers = new Map(); - const EVENT_NAME = "componentFeatureLoad"; - const eventProvider$6 = new EventProvider(); - const featureLoadEventName = name => `${EVENT_NAME}_${name}`; - const getFeature = name => { - return features.get(name); - }; - const getComponentFeature = name => { - return componentFeatures.get(name); - }; - const subscribeForFeatureLoad = (name, klass, callback) => { - const subscriber = subscribers.get(klass); - const isSubscribed = subscriber?.includes(name); - if (isSubscribed) { - return; - } - if (!subscriber) { - subscribers.set(klass, [name]); - } else { - subscriber.push(name); - } - eventProvider$6.attachEvent(featureLoadEventName(name), callback); - }; - - const styleData$7 = { - packageName: "@ui5/webcomponents-base", - fileName: "FontFace.css", - content: `@font-face{font-family:"72";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular.woff2?ui5-webcomponents) format("woff2"),local("72");unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular-full.woff2?ui5-webcomponents) format("woff2"),local('72-full')}@font-face{font-family:"72";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Bold';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Boldfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Light';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light.woff2?ui5-webcomponents) format("woff2"),local('72-Light');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Lightfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72Mono';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular.woff2?ui5-webcomponents) format('woff2'),local('72Mono');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Monofull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:'72Mono-Bold';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold.woff2?ui5-webcomponents) format('woff2'),local('72Mono-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Mono-Boldfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72Black";font-style:bold;font-weight:900;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black.woff2?ui5-webcomponents) format("woff2"),local('72Black');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Blackfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72-SemiboldDuplex";src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-SemiboldDuplex.woff2?ui5-webcomponents) format("woff2"),local('72-SemiboldDuplex');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}`, - }; - - const styleData$6 = { - packageName: "@ui5/webcomponents-base", - fileName: "OverrideFontFace.css", - content: `@font-face{font-family:'72override';unicode-range:U+0102-0103,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EB7,U+1EB8-1EC7,U+1EC8-1ECB,U+1ECC-1EE3,U+1EE4-1EF1,U+1EF4-1EF7;src:local('Arial'),local('Helvetica'),local('sans-serif')}`, - }; - - const assetParameters = { "themes": { "default": "sap_horizon", "all": ["sap_fiori_3", "sap_fiori_3_dark", "sap_fiori_3_hcb", "sap_fiori_3_hcw", "sap_horizon", "sap_horizon_dark", "sap_horizon_hcb", "sap_horizon_hcw", "sap_horizon_exp", "sap_horizon_dark_exp", "sap_horizon_hcb_exp", "sap_horizon_hcw_exp"] }, "languages": { "default": "en", "all": ["ar", "bg", "ca", "cnr", "cs", "cy", "da", "de", "el", "en", "en_GB", "en_US_sappsd", "en_US_saprigi", "en_US_saptrc", "es", "es_MX", "et", "fi", "fr", "fr_CA", "hi", "hr", "hu", "in", "it", "iw", "ja", "kk", "ko", "lt", "lv", "mk", "ms", "nl", "no", "pl", "pt_PT", "pt", "ro", "ru", "sh", "sk", "sl", "sr", "sv", "th", "tr", "uk", "vi", "zh_CN", "zh_TW"] }, "locales": { "default": "en", "all": ["ar", "ar_EG", "ar_SA", "bg", "ca", "cnr", "cs", "da", "de", "de_AT", "de_CH", "el", "el_CY", "en", "en_AU", "en_GB", "en_HK", "en_IE", "en_IN", "en_NZ", "en_PG", "en_SG", "en_ZA", "es", "es_AR", "es_BO", "es_CL", "es_CO", "es_MX", "es_PE", "es_UY", "es_VE", "et", "fa", "fi", "fr", "fr_BE", "fr_CA", "fr_CH", "fr_LU", "he", "hi", "hr", "hu", "id", "it", "it_CH", "ja", "kk", "ko", "lt", "lv", "ms", "mk", "nb", "nl", "nl_BE", "pl", "pt", "pt_PT", "ro", "ru", "ru_UA", "sk", "sl", "sr", "sr_Latn", "sv", "th", "tr", "uk", "vi", "zh_CN", "zh_HK", "zh_SG", "zh_TW"] } }; - const DEFAULT_THEME = assetParameters.themes.default; - const SUPPORTED_THEMES = assetParameters.themes.all; - const DEFAULT_LANGUAGE = assetParameters.languages.default; - const DEFAULT_LOCALE = assetParameters.locales.default; - const SUPPORTED_LOCALES = assetParameters.locales.all; - - const isSSR$1 = typeof document === "undefined"; - const internals = { - search() { - if (isSSR$1) { - return ""; - } - return window.location.search; - }, - }; - const getLocationHref = () => { - if (isSSR$1) { - return ""; - } - return window.location.href; - }; - const getLocationSearch = () => { - return internals.search(); - }; - - const getMetaTagValue = (metaTagName) => { - const metaTag = document.querySelector(`META[name="${metaTagName}"]`), metaTagContent = metaTag && metaTag.getAttribute("content"); - return metaTagContent; - }; - const validateThemeOrigin = (origin) => { - const allowedOrigins = getMetaTagValue("sap-allowedThemeOrigins"); - return allowedOrigins && allowedOrigins.split(",").some(allowedOrigin => { - return allowedOrigin === "*" || origin === allowedOrigin.trim(); - }); - }; - const buildCorrectUrl = (oldUrl, newOrigin) => { - const oldUrlPath = new URL(oldUrl).pathname; - return new URL(oldUrlPath, newOrigin).toString(); - }; - const validateThemeRoot = (themeRoot) => { - let resultUrl; - try { - if (themeRoot.startsWith(".") || themeRoot.startsWith("/")) { - // Handle relative url - // new URL("/newExmPath", "http://example.com/exmPath") => http://example.com/newExmPath - // new URL("./newExmPath", "http://example.com/exmPath") => http://example.com/exmPath/newExmPath - // new URL("../newExmPath", "http://example.com/exmPath") => http://example.com/newExmPath - resultUrl = new URL(themeRoot, getLocationHref()).toString(); - } - else { - const themeRootURL = new URL(themeRoot); - const origin = themeRootURL.origin; - if (origin && validateThemeOrigin(origin)) { - // If origin is allowed, use it - resultUrl = themeRootURL.toString(); - } - else { - // If origin is not allow and the URL is not relative, we have to replace the origin - // with current location - resultUrl = buildCorrectUrl(themeRootURL.toString(), getLocationHref()); - } - } - if (!resultUrl.endsWith("/")) { - resultUrl = `${resultUrl}/`; - } - return `${resultUrl}UI5/`; - } - catch (e) { - // Catch if URL is not correct - } - }; - - /** - * Different types of AnimationMode. - * - * @public - */ - var AnimationMode; - (function (AnimationMode) { - /** - * @public - */ - AnimationMode["Full"] = "full"; - /** - * @public - */ - AnimationMode["Basic"] = "basic"; - /** - * @public - */ - AnimationMode["Minimal"] = "minimal"; - /** - * @public - */ - AnimationMode["None"] = "none"; - })(AnimationMode || (AnimationMode = {})); - var AnimationMode$1 = AnimationMode; - - const eventProvider$5 = new EventProvider(); - const CONFIGURATION_RESET = "configurationReset"; - const attachConfigurationReset = (listener) => { - eventProvider$5.attachEvent(CONFIGURATION_RESET, listener); - }; - - let initialized = false; - let initialConfig = { - animationMode: AnimationMode$1.Full, - theme: DEFAULT_THEME, - themeRoot: undefined, - rtl: undefined, - language: undefined, - timezone: undefined, - calendarType: undefined, - secondaryCalendarType: undefined, - noConflict: false, // no URL - formatSettings: {}, - fetchDefaultLanguage: false, - defaultFontLoading: true, - enableDefaultTooltips: true, - }; - const getTheme$1 = () => { - initConfiguration(); - return initialConfig.theme; - }; - const getThemeRoot$1 = () => { - initConfiguration(); - return initialConfig.themeRoot; - }; - const getLanguage$1 = () => { - initConfiguration(); - return initialConfig.language; - }; - /** - * Returns if the default language, that is inlined at build time, - * should be fetched over the network instead. - * @returns {Boolean} - */ - const getFetchDefaultLanguage$1 = () => { - initConfiguration(); - return initialConfig.fetchDefaultLanguage; - }; - const getNoConflict$1 = () => { - initConfiguration(); - return initialConfig.noConflict; - }; - const getDefaultFontLoading$1 = () => { - initConfiguration(); - return initialConfig.defaultFontLoading; - }; - const booleanMapping = new Map(); - booleanMapping.set("true", true); - booleanMapping.set("false", false); - const parseConfigurationScript = () => { - const configScript = document.querySelector("[data-ui5-config]") || document.querySelector("[data-id='sap-ui-config']"); // for backward compatibility - let configJSON; - if (configScript) { - try { - configJSON = JSON.parse(configScript.innerHTML); - } - catch (err) { - console.warn("Incorrect data-sap-ui-config format. Please use JSON"); /* eslint-disable-line */ - } - if (configJSON) { - initialConfig = fnMerge(initialConfig, configJSON); - } - } - }; - const parseURLParameters = () => { - const params = new URLSearchParams(getLocationSearch()); - // Process "sap-*" params first - params.forEach((value, key) => { - const parts = key.split("sap-").length; - if (parts === 0 || parts === key.split("sap-ui-").length) { - return; - } - applyURLParam(key, value, "sap"); - }); - // Process "sap-ui-*" params - params.forEach((value, key) => { - if (!key.startsWith("sap-ui")) { - return; - } - applyURLParam(key, value, "sap-ui"); - }); - }; - const normalizeThemeRootParamValue = (value) => { - const themeRoot = value.split("@")[1]; - return validateThemeRoot(themeRoot); - }; - const normalizeThemeParamValue = (param, value) => { - if (param === "theme" && value.includes("@")) { // the theme parameter might have @ in the value - strip this - return value.split("@")[0]; - } - return value; - }; - const applyURLParam = (key, value, paramType) => { - const lowerCaseValue = value.toLowerCase(); - const param = key.split(`${paramType}-`)[1]; - if (booleanMapping.has(value)) { - value = booleanMapping.get(lowerCaseValue); - } - if (param === "theme") { - initialConfig.theme = normalizeThemeParamValue(param, value); - if (value && value.includes("@")) { - initialConfig.themeRoot = normalizeThemeRootParamValue(value); - } - } - else { - initialConfig[param] = value; - } - }; - const applyOpenUI5Configuration = () => { - const openUI5Support = getFeature("OpenUI5Support"); - if (!openUI5Support || !openUI5Support.isOpenUI5Detected()) { - return; - } - const OpenUI5Config = openUI5Support.getConfigurationSettingsObject(); - initialConfig = fnMerge(initialConfig, OpenUI5Config); - }; - const initConfiguration = () => { - if (typeof document === "undefined" || initialized) { - return; - } - resetConfiguration(); - initialized = true; - }; - /** - * Internaly exposed method to enable configurations in tests. - * @private - */ - const resetConfiguration = (testEnv) => { - // 1. Lowest priority - configuration script - parseConfigurationScript(); - // 2. URL parameters overwrite configuration script parameters - parseURLParameters(); - // 3. If OpenUI5 is detected, it has the highest priority - applyOpenUI5Configuration(); - }; - - let defaultFontLoading; - attachConfigurationReset(() => { - defaultFontLoading = undefined; - }); - /** - * Returns if the "defaultFontLoading" configuration is set. - * @public - * @returns { boolean } - */ - const getDefaultFontLoading = () => { - if (defaultFontLoading === undefined) { - defaultFontLoading = getDefaultFontLoading$1(); - } - return defaultFontLoading; - }; - - const insertFontFace = () => { - const openUI5Support = getFeature("OpenUI5Support"); - // Only set the main font if there is no OpenUI5 support, or there is, but OpenUI5 is not loaded - if ((!openUI5Support || !openUI5Support.isOpenUI5Detected())) { - insertMainFontFace(); - } - // Always set the override font - OpenUI5 in CSS Vars mode does not set it, unlike the main font - insertOverrideFontFace(); - }; - const insertMainFontFace = () => { - const hasFontStyles = document.querySelector("head>style[data-ui5-font-face]"); - if (!getDefaultFontLoading() || hasFontStyles) { - return; - } - if (!hasStyle("data-ui5-font-face")) { - createStyle(styleData$7, "data-ui5-font-face"); - } - }; - const insertOverrideFontFace = () => { - if (!hasStyle("data-ui5-font-face-override")) { - createStyle(styleData$6, "data-ui5-font-face-override"); - } - }; - - const styleData$5 = { - packageName: "@ui5/webcomponents-base", - fileName: "SystemCSSVars.css", - content: `:root{--_ui5_content_density:cozy}.sapUiSizeCompact,.ui5-content-density-compact,[data-ui5-compact-size]{--_ui5_content_density:compact}`, - }; - - const insertSystemCSSVars = () => { - if (!hasStyle("data-ui5-system-css-vars")) { - createStyle(styleData$5, "data-ui5-system-css-vars"); - } - }; - - const MAX_PROCESS_COUNT = 10; - class RenderQueue { - constructor() { - this.list = []; // Used to store the web components in order - this.lookup = new Set(); // Used for faster search - } - add(webComponent) { - if (this.lookup.has(webComponent)) { - return; - } - this.list.push(webComponent); - this.lookup.add(webComponent); - } - remove(webComponent) { - if (!this.lookup.has(webComponent)) { - return; - } - this.list = this.list.filter(item => item !== webComponent); - this.lookup.delete(webComponent); - } - shift() { - const webComponent = this.list.shift(); - if (webComponent) { - this.lookup.delete(webComponent); - return webComponent; - } - } - isEmpty() { - return this.list.length === 0; - } - isAdded(webComponent) { - return this.lookup.has(webComponent); - } - /** - * Processes the whole queue by executing the callback on each component, - * while also imposing restrictions on how many times a component may be processed. - * - * @param callback - function with one argument (the web component to be processed) - */ - process(callback) { - let webComponent; - const stats = new Map(); - webComponent = this.shift(); - while (webComponent) { - const timesProcessed = stats.get(webComponent) || 0; - if (timesProcessed > MAX_PROCESS_COUNT) { - throw new Error(`Web component processed too many times this task, max allowed is: ${MAX_PROCESS_COUNT}`); - } - callback(webComponent); - stats.set(webComponent, timesProcessed + 1); - webComponent = this.shift(); - } - } - } - - const rtlAwareSet = new Set(); - const markAsRtlAware = (klass) => { - rtlAwareSet.add(klass); - }; - const isRtlAware = (klass) => { - return rtlAwareSet.has(klass); - }; - - const registeredElements = new Set(); - const eventProvider$4 = new EventProvider(); - const invalidatedWebComponents = new RenderQueue(); // Queue for invalidated web components - let renderTaskPromise, renderTaskPromiseResolve; - let mutationObserverTimer; - let queuePromise; - /** - * Schedules a render task (if not already scheduled) to render the component - * - * @param webComponent - * @returns {Promise} - */ - const renderDeferred = async (webComponent) => { - // Enqueue the web component - invalidatedWebComponents.add(webComponent); - // Schedule a rendering task - await scheduleRenderTask(); - }; - /** - * Renders a component synchronously and adds it to the registry of rendered components - * - * @param webComponent - */ - const renderImmediately = (webComponent) => { - eventProvider$4.fireEvent("beforeComponentRender", webComponent); - registeredElements.add(webComponent); - webComponent._render(); - }; - /** - * Cancels the rendering of a component, if awaiting to be rendered, and removes it from the registry of rendered components - * - * @param webComponent - */ - const cancelRender = (webComponent) => { - invalidatedWebComponents.remove(webComponent); - registeredElements.delete(webComponent); - }; - /** - * Schedules a rendering task, if not scheduled already - */ - const scheduleRenderTask = async () => { - if (!queuePromise) { - queuePromise = new Promise(resolve => { - window.requestAnimationFrame(() => { - // Render all components in the queue - // console.log(`--------------------RENDER TASK START------------------------------`); // eslint-disable-line - invalidatedWebComponents.process(renderImmediately); - // console.log(`--------------------RENDER TASK END------------------------------`); // eslint-disable-line - // Resolve the promise so that callers of renderDeferred can continue - queuePromise = null; - resolve(); - // Wait for Mutation observer before the render task is considered finished - if (!mutationObserverTimer) { - mutationObserverTimer = setTimeout(() => { - mutationObserverTimer = undefined; - if (invalidatedWebComponents.isEmpty()) { - _resolveTaskPromise(); - } - }, 200); - } - }); - }); - } - await queuePromise; - }; - /** - * return a promise that will be resolved once all invalidated web components are rendered - */ - const whenDOMUpdated = () => { - if (renderTaskPromise) { - return renderTaskPromise; - } - renderTaskPromise = new Promise(resolve => { - renderTaskPromiseResolve = resolve; - window.requestAnimationFrame(() => { - if (invalidatedWebComponents.isEmpty()) { - renderTaskPromise = undefined; - resolve(); - } - }); - }); - return renderTaskPromise; - }; - const whenAllCustomElementsAreDefined = () => { - const definedPromises = getAllRegisteredTags().map(tag => customElements.whenDefined(tag)); - return Promise.all(definedPromises); - }; - const renderFinished = async () => { - await whenAllCustomElementsAreDefined(); - await whenDOMUpdated(); - }; - const _resolveTaskPromise = () => { - if (!invalidatedWebComponents.isEmpty()) { - // More updates are pending. Resolve will be called again - return; - } - if (renderTaskPromiseResolve) { - renderTaskPromiseResolve(); - renderTaskPromiseResolve = undefined; - renderTaskPromise = undefined; - } - }; - /** - * Re-renders all UI5 Elements on the page, with the option to specify filters to rerender only some components. - * - * Usage: - * reRenderAllUI5Elements() -> re-renders all components - * reRenderAllUI5Elements({tag: "ui5-button"}) -> re-renders only instances of ui5-button - * reRenderAllUI5Elements({rtlAware: true}) -> re-renders only rtlAware components - * reRenderAllUI5Elements({languageAware: true}) -> re-renders only languageAware components - * reRenderAllUI5Elements({themeAware: true}) -> re-renders only themeAware components - * reRenderAllUI5Elements({rtlAware: true, languageAware: true}) -> re-renders components that are rtlAware or languageAware - * etc... - * - * @public - * @param {object|undefined} filters - Object with keys that can be "rtlAware" or "languageAware" - * @returns {Promise} - */ - const reRenderAllUI5Elements = async (filters) => { - registeredElements.forEach((element) => { - const ctor = element.constructor; - const tag = ctor.getMetadata().getTag(); - const rtlAware = isRtlAware(ctor); - const languageAware = ctor.getMetadata().isLanguageAware(); - const themeAware = ctor.getMetadata().isThemeAware(); - if (!filters || (filters.tag === tag) || (filters.rtlAware && rtlAware) || (filters.languageAware && languageAware) || (filters.themeAware && themeAware)) { - renderDeferred(element); - } - }); - await renderFinished(); - }; - - const eventProvider$3 = new EventProvider(); - const THEME_REGISTERED = "themeRegistered"; - const attachThemeRegistered = (listener) => { - eventProvider$3.attachEvent(THEME_REGISTERED, listener); - }; - const fireThemeRegistered = (theme) => { - return eventProvider$3.fireEvent(THEME_REGISTERED, theme); - }; - - const themeStyles = new Map(); - const loaders$3 = new Map(); - const customLoaders = new Map(); - const registeredPackages = new Set(); - const registeredThemes = new Set(); - const registerThemePropertiesLoader = (packageName, themeName, loader) => { - loaders$3.set(`${packageName}/${themeName}`, loader); - registeredPackages.add(packageName); - registeredThemes.add(themeName); - fireThemeRegistered(themeName); - }; - const getThemeProperties = async (packageName, themeName, externalThemeName) => { - const cacheKey = `${packageName}_${themeName}_${externalThemeName || ""}`; - const cachedStyleData = themeStyles.get(cacheKey); - if (cachedStyleData !== undefined) { // it's valid for style to be an empty string - return cachedStyleData; - } - if (!registeredThemes.has(themeName)) { - const regThemesStr = [...registeredThemes.values()].join(", "); - console.warn(`You have requested a non-registered theme ${themeName} - falling back to ${DEFAULT_THEME}. Registered themes are: ${regThemesStr}`); /* eslint-disable-line */ - return _getThemeProperties(packageName, DEFAULT_THEME); - } - const [style, customStyle] = await Promise.all([ - _getThemeProperties(packageName, themeName), - externalThemeName ? _getThemeProperties(packageName, externalThemeName, true) : undefined, - ]); - const styleData = mergeStyles(style, customStyle); - if (styleData) { - themeStyles.set(cacheKey, styleData); - } - return styleData; - }; - const _getThemeProperties = async (packageName, themeName, forCustomTheme = false) => { - const loadersMap = forCustomTheme ? customLoaders : loaders$3; - const loader = loadersMap.get(`${packageName}/${themeName}`); - if (!loader) { - // no themes for package - if (!forCustomTheme) { - console.error(`Theme [${themeName}] not registered for package [${packageName}]`); /* eslint-disable-line */ - } - return; - } - let data; - try { - data = await loader(themeName); - } - catch (error) { - const e = error; - console.error(packageName, e.message); /* eslint-disable-line */ - return; - } - const themeProps = data._ || data; // Refactor: remove _ everywhere - return themeProps; - }; - const getRegisteredPackages = () => { - return registeredPackages; - }; - const isThemeRegistered = (theme) => { - return registeredThemes.has(theme); - }; - - const warnings = new Set(); - const getThemeMetadata = () => { - // Check if the class was already applied, most commonly to the link/style tag with the CSS Variables - let el = document.querySelector(".sapThemeMetaData-Base-baseLib") || document.querySelector(".sapThemeMetaData-UI5-sap-ui-core"); - if (el) { - return getComputedStyle(el).backgroundImage; - } - el = document.createElement("span"); - el.style.display = "none"; - // Try with sapThemeMetaData-Base-baseLib first - el.classList.add("sapThemeMetaData-Base-baseLib"); - document.body.appendChild(el); - let metadata = getComputedStyle(el).backgroundImage; - // Try with sapThemeMetaData-UI5-sap-ui-core only if the previous selector was not found - if (metadata === "none") { - el.classList.add("sapThemeMetaData-UI5-sap-ui-core"); - metadata = getComputedStyle(el).backgroundImage; - } - document.body.removeChild(el); - return metadata; - }; - const parseThemeMetadata = (metadataString) => { - const params = /\(["']?data:text\/plain;utf-8,(.*?)['"]?\)$/i.exec(metadataString); - if (params && params.length >= 2) { - let paramsString = params[1]; - paramsString = paramsString.replace(/\\"/g, `"`); - if (paramsString.charAt(0) !== "{" && paramsString.charAt(paramsString.length - 1) !== "}") { - try { - paramsString = decodeURIComponent(paramsString); - } - catch (ex) { - if (!warnings.has("decode")) { - console.warn("Malformed theme metadata string, unable to decodeURIComponent"); // eslint-disable-line - warnings.add("decode"); - } - return; - } - } - try { - return JSON.parse(paramsString); - } - catch (ex) { - if (!warnings.has("parse")) { - console.warn("Malformed theme metadata string, unable to parse JSON"); // eslint-disable-line - warnings.add("parse"); - } - } - } - }; - const processThemeMetadata = (metadata) => { - let themeName; - let baseThemeName; - try { - themeName = metadata.Path.match(/\.([^.]+)\.css_variables$/)[1]; - baseThemeName = metadata.Extends[0]; - } - catch (ex) { - if (!warnings.has("object")) { - console.warn("Malformed theme metadata Object", metadata); // eslint-disable-line - warnings.add("object"); - } - return; - } - return { - themeName, - baseThemeName, - }; - }; - const getThemeDesignerTheme = () => { - const metadataString = getThemeMetadata(); - if (!metadataString || metadataString === "none") { - return; - } - const metadata = parseThemeMetadata(metadataString); - if (metadata) { - return processThemeMetadata(metadata); - } - }; - - const eventProvider$2 = new EventProvider(); - const THEME_LOADED = "themeLoaded"; - const fireThemeLoaded = (theme) => { - return eventProvider$2.fireEvent(THEME_LOADED, theme); - }; - - /** - * Creates a `` tag in the `` tag - * @param href - the CSS - * @param attributes - optional attributes to add to the tag - */ - const createLinkInHead = (href, attributes) => { - const link = document.createElement("link"); - link.type = "text/css"; - link.rel = "stylesheet"; - if (attributes) { - Object.entries(attributes).forEach(pair => link.setAttribute(...pair)); - } - link.href = href; - document.head.appendChild(link); - return new Promise(resolve => { - link.addEventListener("load", resolve); - link.addEventListener("error", resolve); // intended - }); - }; - - let currThemeRoot; - attachConfigurationReset(() => { - currThemeRoot = undefined; - }); - /** - * Returns the current theme root. - * - * @public - * @since 1.14.0 - * @returns { string } the current theme root - */ - const getThemeRoot = () => { - if (currThemeRoot === undefined) { - currThemeRoot = getThemeRoot$1(); - } - return currThemeRoot; - }; - const formatThemeLink = (theme) => { - return `${getThemeRoot()}Base/baseLib/${theme}/css_variables.css`; // theme root is always set at this point. - }; - const attachCustomThemeStylesToHead = async (theme) => { - const link = document.querySelector(`[sap-ui-webcomponents-theme="${theme}"]`); - if (link) { - document.head.removeChild(link); - } - await createLinkInHead(formatThemeLink(theme), { "sap-ui-webcomponents-theme": theme }); - }; - - const BASE_THEME_PACKAGE = "@ui5/webcomponents-theming"; - const isThemeBaseRegistered = () => { - const registeredPackages = getRegisteredPackages(); - return registeredPackages.has(BASE_THEME_PACKAGE); - }; - const loadThemeBase = async (theme) => { - if (!isThemeBaseRegistered()) { - return; - } - const cssData = await getThemeProperties(BASE_THEME_PACKAGE, theme); - if (cssData) { - createOrUpdateStyle(cssData, "data-ui5-theme-properties", BASE_THEME_PACKAGE, theme); - } - }; - const deleteThemeBase = () => { - removeStyle("data-ui5-theme-properties", BASE_THEME_PACKAGE); - }; - const loadComponentPackages = async (theme, externalThemeName) => { - const registeredPackages = getRegisteredPackages(); - const packagesStylesPromises = [...registeredPackages].map(async (packageName) => { - if (packageName === BASE_THEME_PACKAGE) { - return; - } - const cssData = await getThemeProperties(packageName, theme, externalThemeName); - if (cssData) { - createOrUpdateStyle(cssData, `data-ui5-component-properties-${getCurrentRuntimeIndex()}`, packageName); - } - }); - return Promise.all(packagesStylesPromises); - }; - const detectExternalTheme = async (theme) => { - // If theme designer theme is detected, use this - const extTheme = getThemeDesignerTheme(); - if (extTheme) { - return extTheme; - } - // If OpenUI5Support is enabled, try to find out if it loaded variables - const openUI5Support = getFeature("OpenUI5Support"); - if (openUI5Support && openUI5Support.isOpenUI5Detected()) { - const varsLoaded = openUI5Support.cssVariablesLoaded(); - if (varsLoaded) { - return { - themeName: openUI5Support.getConfigurationSettingsObject()?.theme, // just themeName - baseThemeName: "", // baseThemeName is only relevant for custom themes - }; - } - } - else if (getThemeRoot()) { - await attachCustomThemeStylesToHead(theme); - return getThemeDesignerTheme(); - } - }; - const applyTheme = async (theme) => { - const extTheme = await detectExternalTheme(theme); - // Only load theme_base properties if there is no externally loaded theme, or there is, but it is not being loaded - if (!extTheme || theme !== extTheme.themeName) { - await loadThemeBase(theme); - } - else { - deleteThemeBase(); - } - // Always load component packages properties. For non-registered themes, try with the base theme, if any - const packagesTheme = isThemeRegistered(theme) ? theme : extTheme && extTheme.baseThemeName; - await loadComponentPackages(packagesTheme || DEFAULT_THEME, extTheme && extTheme.themeName === theme ? theme : undefined); - fireThemeLoaded(theme); - }; - - let curTheme; - attachConfigurationReset(() => { - curTheme = undefined; - }); - /** - * Returns the current theme. - * @public - * @returns {string} the current theme name - */ - const getTheme = () => { - if (curTheme === undefined) { - curTheme = getTheme$1(); - } - return curTheme; - }; - /** - * Returns if the currently set theme is part of legacy theme families ("sap_fiori_3"). - * **Note**: in addition, the method checks the base theme of a custom theme, built via the ThemeDesigner. - * - * @private - * @returns { boolean } - */ - const isLegacyThemeFamily = () => { - const currentTheme = getTheme(); - if (!isKnownTheme(currentTheme)) { - return !getThemeDesignerTheme()?.baseThemeName?.startsWith("sap_horizon"); - } - return !currentTheme.startsWith("sap_horizon"); - }; - const isKnownTheme = (theme) => SUPPORTED_THEMES.includes(theme); - - let listenerAttached = false; - const fixSafariActiveState = () => { - if (isSafari() && isIOS() && !listenerAttached) { - // Safari on iOS does not use the :active state unless there is a touchstart event handler on the element - document.body.addEventListener("touchstart", () => { }); - listenerAttached = true; - } - }; - - let booted = false; - let bootPromise; - const eventProvider$1 = new EventProvider(); - const boot = async () => { - if (bootPromise !== undefined) { - return bootPromise; - } - const bootExecutor = async (resolve) => { - registerCurrentRuntime(); - if (typeof document === "undefined") { - resolve(); - return; - } - attachThemeRegistered(onThemeRegistered); - const openUI5Support = getFeature("OpenUI5Support"); - const isOpenUI5Loaded = openUI5Support ? openUI5Support.isOpenUI5Detected() : false; - const f6Navigation = getFeature("F6Navigation"); - if (openUI5Support) { - await openUI5Support.init(); - } - if (f6Navigation && !isOpenUI5Loaded) { - f6Navigation.init(); - } - await whenDOMReady(); - await applyTheme(getTheme()); - openUI5Support && openUI5Support.attachListeners(); - insertFontFace(); - insertSystemCSSVars(); - fixSafariActiveState(); - resolve(); - booted = true; - eventProvider$1.fireEvent("boot"); - }; - bootPromise = new Promise(bootExecutor); - return bootPromise; - }; - /** - * Callback, executed after theme properties registration - * to apply the newly registered theme. - * @private - * @param { string } theme - */ - const onThemeRegistered = (theme) => { - if (booted && theme === getTheme()) { // getTheme should only be called if "booted" is true - applyTheme(getTheme()); - } - }; - - const kebabToCamelMap = new Map(); - const camelToKebabMap = new Map(); - const kebabToPascalMap = new Map(); - const kebabToCamelCase = (string) => { - if (!kebabToCamelMap.has(string)) { - const result = toCamelCase(string.split("-")); - kebabToCamelMap.set(string, result); - } - return kebabToCamelMap.get(string); - }; - const camelToKebabCase = (string) => { - if (!camelToKebabMap.has(string)) { - const result = string.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); - camelToKebabMap.set(string, result); - } - return camelToKebabMap.get(string); - }; - const toCamelCase = (parts) => { - return parts.map((string, index) => { - return index === 0 ? string.toLowerCase() : string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); - }).join(""); - }; - const kebabToPascalCase = (src) => { - const cachedName = kebabToPascalMap.get(src); - if (cachedName) { - return cachedName; - } - const camelStr = kebabToCamelCase(src); - const result = camelStr.charAt(0).toUpperCase() + camelStr.slice(1); - kebabToPascalMap.set(src, result); - return result; - }; - - /** - * Determines the slot to which a node should be assigned - * @param node Text node or HTML element - * @returns {string} - */ - const getSlotName = (node) => { - // Text nodes can only go to the default slot - if (!(node instanceof HTMLElement)) { - return "default"; - } - // Discover the slot based on the real slot name (f.e. footer => footer, or content-32 => content) - const slot = node.getAttribute("slot"); - if (slot) { - const match = slot.match(/^(.+?)-\d+$/); - return match ? match[1] : slot; - } - // Use default slot as a fallback - return "default"; - }; - const getSlottedNodes = (node) => { - if (node instanceof HTMLSlotElement) { - return node.assignedNodes({ flatten: true }).filter(item => item instanceof HTMLElement); - } - return [node]; - }; - const getSlottedNodesList = (nodeList) => { - return nodeList.reduce((acc, curr) => acc.concat(getSlottedNodes(curr)), []); - }; - - /** - * @class - * @public - */ - class UI5ElementMetadata { - constructor(metadata) { - this.metadata = metadata; - } - getInitialState() { - if (Object.prototype.hasOwnProperty.call(this, "_initialState")) { - return this._initialState; - } - const initialState = {}; - const slotsAreManaged = this.slotsAreManaged(); - // Initialize slots - if (slotsAreManaged) { - const slots = this.getSlots(); - for (const [slotName, slotData] of Object.entries(slots)) { // eslint-disable-line - const propertyName = slotData.propertyName || slotName; - initialState[propertyName] = []; - initialState[kebabToCamelCase(propertyName)] = initialState[propertyName]; - } - } - this._initialState = initialState; - return initialState; - } - /** - * Validates the slot's value and returns it if correct - * or throws an exception if not. - * **Note:** Only intended for use by UI5Element.js - * @public - */ - static validateSlotValue(value, slotData) { - return validateSingleSlot(value, slotData); - } - /** - * Returns the tag of the UI5 Element without the scope - * @public - */ - getPureTag() { - return this.metadata.tag || ""; - } - /** - * Returns the tag of the UI5 Element without the scope - * @private - */ - getFeatures() { - return this.metadata.features || []; - } - /** - * Returns the tag of the UI5 Element - * @public - */ - getTag() { - const pureTag = this.metadata.tag; - if (!pureTag) { - return ""; - } - const suffix = getEffectiveScopingSuffixForTag(pureTag); - if (!suffix) { - return pureTag; - } - return `${pureTag}-${suffix}`; - } - /** - * Determines whether a property should have an attribute counterpart - * @public - * @param propName - */ - hasAttribute(propName) { - const propData = this.getProperties()[propName]; - return propData.type !== Object && propData.type !== Array && !propData.noAttribute; - } - /** - * Returns an array with the properties of the UI5 Element (in camelCase) - * @public - */ - getPropertiesList() { - return Object.keys(this.getProperties()); - } - /** - * Returns an array with the attributes of the UI5 Element (in kebab-case) - * @public - */ - getAttributesList() { - return this.getPropertiesList().filter(this.hasAttribute.bind(this)).map(camelToKebabCase); - } - /** - * Determines whether this UI5 Element has a default slot of type Node, therefore can slot text - */ - canSlotText() { - return (this.getSlots().default)?.type === Node; - } - /** - * Determines whether this UI5 Element supports any slots - * @public - */ - hasSlots() { - return !!Object.entries(this.getSlots()).length; - } - /** - * Determines whether this UI5 Element supports any slots with "individualSlots: true" - * @public - */ - hasIndividualSlots() { - return this.slotsAreManaged() && Object.values(this.getSlots()).some(slotData => slotData.individualSlots); - } - /** - * Determines whether this UI5 Element needs to invalidate if children are added/removed/changed - * @public - */ - slotsAreManaged() { - return !!this.metadata.managedSlots; - } - /** - * Determines whether this control supports F6 fast navigation - * @public - */ - supportsF6FastNavigation() { - return !!this.metadata.fastNavigation; - } - /** - * Returns an object with key-value pairs of properties and their metadata definitions - * @public - */ - getProperties() { - if (!this.metadata.properties) { - this.metadata.properties = {}; - } - return this.metadata.properties; - } - /** - * Returns an object with key-value pairs of events and their metadata definitions - * @public - */ - getEvents() { - if (!this.metadata.events) { - this.metadata.events = {}; - } - return this.metadata.events; - } - /** - * Returns an object with key-value pairs of slots and their metadata definitions - * @public - */ - getSlots() { - if (!this.metadata.slots) { - this.metadata.slots = {}; - } - return this.metadata.slots; - } - /** - * Determines whether this UI5 Element has any translatable texts (needs to be invalidated upon language change) - */ - isLanguageAware() { - return !!this.metadata.languageAware; - } - /** - * Determines whether this UI5 Element has any theme dependant carachteristics. - */ - isThemeAware() { - return !!this.metadata.themeAware; - } - /** - * Determines whether this UI5 Element needs CLDR assets to be fetched to work correctly - */ - needsCLDR() { - return !!this.metadata.cldr; - } - getShadowRootOptions() { - return this.metadata.shadowRootOptions || {}; - } - /** - * Determines whether this UI5 Element has any theme dependant carachteristics. - */ - isFormAssociated() { - return !!this.metadata.formAssociated; - } - /** - * Matches a changed entity (property/slot) with the given name against the "invalidateOnChildChange" configuration - * and determines whether this should cause and invalidation - * - * @param slotName the name of the slot in which a child was changed - * @param type the type of change in the child: "property" or "slot" - * @param name the name of the property/slot that changed - */ - shouldInvalidateOnChildChange(slotName, type, name) { - const config = this.getSlots()[slotName].invalidateOnChildChange; - // invalidateOnChildChange was not set in the slot metadata - by default child changes do not affect the component - if (config === undefined) { - return false; - } - // The simple format was used: invalidateOnChildChange: true/false; - if (typeof config === "boolean") { - return config; - } - // The complex format was used: invalidateOnChildChange: { properties, slots } - if (typeof config === "object") { - // A property was changed - if (type === "property") { - // The config object does not have a properties field - if (config.properties === undefined) { - return false; - } - // The config object has the short format: properties: true/false - if (typeof config.properties === "boolean") { - return config.properties; - } - // The config object has the complex format: properties: [...] - if (Array.isArray(config.properties)) { - return config.properties.includes(name); - } - throw new Error("Wrong format for invalidateOnChildChange.properties: boolean or array is expected"); - } - // A slot was changed - if (type === "slot") { - // The config object does not have a slots field - if (config.slots === undefined) { - return false; - } - // The config object has the short format: slots: true/false - if (typeof config.slots === "boolean") { - return config.slots; - } - // The config object has the complex format: slots: [...] - if (Array.isArray(config.slots)) { - return config.slots.includes(name); - } - throw new Error("Wrong format for invalidateOnChildChange.slots: boolean or array is expected"); - } - } - throw new Error("Wrong format for invalidateOnChildChange: boolean or object is expected"); - } - getI18n() { - if (!this.metadata.i18n) { - this.metadata.i18n = {}; - } - return this.metadata.i18n; - } - } - const validateSingleSlot = (value, slotData) => { - value && getSlottedNodes(value).forEach(el => { - if (!(el instanceof slotData.type)) { - throw new Error(`The element is not of type ${slotData.type.toString()}`); - } - }); - return value; - }; - - const getEventProvider = () => getSharedResource("CustomStyle.eventProvider", new EventProvider()); - const CUSTOM_CSS_CHANGE = "CustomCSSChange"; - const attachCustomCSSChange = (listener) => { - getEventProvider().attachEvent(CUSTOM_CSS_CHANGE, listener); - }; - const getCustomCSSFor = () => getSharedResource("CustomStyle.customCSSFor", {}); - attachCustomCSSChange((tag) => { - { - reRenderAllUI5Elements({ tag }); - } - }); - const getCustomCSS = (tag) => { - const customCSSFor = getCustomCSSFor(); - return customCSSFor[tag] ? customCSSFor[tag].join("") : ""; - }; - - const MAX_DEPTH_INHERITED_CLASSES = 10; // TypeScript complains about Infinity and big numbers - const getStylesString = (styles) => { - if (Array.isArray(styles)) { - return styles.filter(style => !!style).flat(MAX_DEPTH_INHERITED_CLASSES).map((style) => { - return typeof style === "string" ? style : style.content; - }).join(" "); - } - return typeof styles === "string" ? styles : styles.content; - }; - - const effectiveStyleMap = new Map(); - attachCustomCSSChange((tag) => { - effectiveStyleMap.delete(`${tag}_normal`); // there is custom CSS only for the component itself, not for its static area part - }); - const getEffectiveStyle = (ElementClass) => { - const tag = ElementClass.getMetadata().getTag(); - const key = `${tag}_normal`; - const openUI5Enablement = getFeature("OpenUI5Enablement"); - if (!effectiveStyleMap.has(key)) { - let busyIndicatorStyles = ""; - if (openUI5Enablement) { - busyIndicatorStyles = getStylesString(openUI5Enablement.getBusyIndicatorStyles()); - } - const customStyle = getCustomCSS(tag) || ""; - const builtInStyles = getStylesString(ElementClass.styles); - const effectiveStyle = `${builtInStyles} ${customStyle} ${busyIndicatorStyles}`; - effectiveStyleMap.set(key, effectiveStyle); - } - return effectiveStyleMap.get(key); // The key is guaranteed to exist - }; - - const constructableStyleMap = new Map(); - attachCustomCSSChange((tag) => { - constructableStyleMap.delete(`${tag}_normal`); // there is custom CSS only for the component itself, not for its static area part - }); - /** - * Returns (and caches) a constructable style sheet for a web component class - * Note: Chrome - * @param ElementClass - * @returns {*} - */ - const getConstructableStyle = (ElementClass) => { - const tag = ElementClass.getMetadata().getTag(); - const key = `${tag}_normal`; - if (!constructableStyleMap.has(key)) { - const styleContent = getEffectiveStyle(ElementClass); - const style = new CSSStyleSheet(); - style.replaceSync(styleContent); - constructableStyleMap.set(key, [style]); - } - return constructableStyleMap.get(key); - }; - - /** - * Updates the shadow root of a UI5Element or its static area item - * @param element - */ - const updateShadowRoot = (element) => { - const ctor = element.constructor; - const shadowRoot = element.shadowRoot; - const renderResult = element.render(); // this is checked before calling updateShadowRoot - if (!shadowRoot) { - console.warn(`There is no shadow root to update`); // eslint-disable-line - return; - } - shadowRoot.adoptedStyleSheets = getConstructableStyle(ctor); - ctor.renderer(renderResult, shadowRoot, { host: element }); - }; - - /** - * The tag prefixes to be ignored. - */ - const tagPrefixes = []; - /** - * Determines whether custom elements with the given tag should be ignored. - * - * @private - * @param { string } tag - */ - const shouldIgnoreCustomElement = (tag) => { - return tagPrefixes.some(pref => tag.startsWith(pref)); - }; - - const observers = new WeakMap(); - /** - * @param node - * @param callback - * @param options - */ - const observeDOMNode = (node, callback, options) => { - const observer = new MutationObserver(callback); - observers.set(node, observer); - observer.observe(node, options); - }; - /** - * @param node - */ - const unobserveDOMNode = (node) => { - const observer = observers.get(node); - if (observer) { - observer.disconnect(); - observers.delete(node); - } - }; - - // Fire these events even with noConflict: true - const excludeList = [ - "value-changed", - "click", - ]; - let noConflict; - attachConfigurationReset(() => { - noConflict = undefined; - }); - const shouldFireOriginalEvent = (eventName) => { - return excludeList.includes(eventName); - }; - const shouldNotFireOriginalEvent = (eventName) => { - const nc = getNoConflict(); - // return !(nc.events && nc.events.includes && nc.events.includes(eventName)); - return !(typeof nc !== "boolean" && nc.events && nc.events.includes && nc.events.includes(eventName)); - }; - /** - * Returns if the "noConflict" configuration is set. - * @public - * @returns { NoConflictData } - */ - const getNoConflict = () => { - if (noConflict === undefined) { - noConflict = getNoConflict$1(); - } - return noConflict; - }; - const skipOriginalEvent = (eventName) => { - const nc = getNoConflict(); - // Always fire these events - if (shouldFireOriginalEvent(eventName)) { - return false; - } - // Read from the configuration - if (nc === true) { - return true; - } - return !shouldNotFireOriginalEvent(eventName); - }; - - const getEffectiveDir = (element) => { - if (element.matches(":dir(rtl)")) { - return "rtl"; - } - return "ltr"; - }; - - // Note: disabled is present in IE so we explicitly allow it here. - // Others, such as title/hidden, we explicitly override, so valid too - const allowList = [ - "disabled", - "title", - "hidden", - "role", - "draggable", - ]; - /** - * Checks whether a property name is valid (does not collide with existing DOM API properties) - * - * @param name - * @returns {boolean} - */ - const isValidPropertyName = (name) => { - if (allowList.includes(name) || name.startsWith("aria")) { - return true; - } - const classes = [ - HTMLElement, - Element, - Node, - ]; - return !classes.some(klass => klass.prototype.hasOwnProperty(name)); // eslint-disable-line - }; - - const arraysAreEqual = (arr1, arr2) => { - if (arr1.length !== arr2.length) { - return false; - } - for (let i = 0; i < arr1.length; i++) { - if (arr1[i] !== arr2[i]) { - return false; - } - } - return true; - }; - - /** - * Runs a component's template with the component's current state, while also scoping HTML - * - * @param template - the template to execute - * @param component - the component - * @public - */ - const executeTemplate = (template, component) => { - const tagsToScope = getTagsToScope(component); - const scope = getCustomElementsScopingSuffix(); - return template.call(component, component, tagsToScope, scope); - }; - /** - * Returns all tags, used inside component's template subject to scoping. - * @param component - the component - * @returns {Array[]} - * @private - */ - const getTagsToScope = (component) => { - const ctor = component.constructor; - const componentTag = ctor.getMetadata().getPureTag(); - const tagsToScope = ctor.getUniqueDependencies().map((dep) => dep.getMetadata().getPureTag()).filter(shouldScopeCustomElement); - if (shouldScopeCustomElement(componentTag)) { - tagsToScope.push(componentTag); - } - return tagsToScope; - }; - - const updateFormValue = (element) => { - if (isInputElement(element)) { - setFormValue(element); - } - }; - const setFormValue = (element) => { - if (!element._internals?.form) { - return; - } - setFormValidity(element); - if (!element.name) { - element._internals?.setFormValue(null); - return; - } - element._internals.setFormValue(element.formFormattedValue); - }; - const setFormValidity = async (element) => { - if (!element._internals?.form) { - return; - } - if (element.formValidity && Object.keys(element.formValidity).some(key => key)) { - const focusRef = await element.formElementAnchor?.(); - element._internals.setValidity(element.formValidity, element.formValidityMessage, focusRef); - } - else { - element._internals.setValidity({}); - } - }; - const isInputElement = (element) => { - return "formFormattedValue" in element && "name" in element; - }; - - const isSSR = typeof document === "undefined"; - const detectNavigatorLanguage = () => { - if (isSSR) { - return DEFAULT_LANGUAGE; - } - const browserLanguages = navigator.languages; - const navigatorLanguage = () => { - return navigator.language; - }; - const rawLocale = (browserLanguages && browserLanguages[0]) || navigatorLanguage(); - return rawLocale || DEFAULT_LANGUAGE; - }; - - const eventProvider = new EventProvider(); - const LANG_CHANGE = "languageChange"; - const attachLanguageChange = (listener) => { - eventProvider.attachEvent(LANG_CHANGE, listener); - }; - - let curLanguage; - let fetchDefaultLanguage; - attachConfigurationReset(() => { - curLanguage = undefined; - fetchDefaultLanguage = undefined; - }); - /** - * Returns the currently configured language, or the browser language as a fallback. - * @public - * @returns {string} - */ - const getLanguage = () => { - if (curLanguage === undefined) { - curLanguage = getLanguage$1(); - } - return curLanguage; - }; - /** - * Returns if the default language, that is inlined, should be fetched over the network. - * @public - * @returns {boolean} - */ - const getFetchDefaultLanguage = () => { - if (fetchDefaultLanguage === undefined) { - fetchDefaultLanguage = getFetchDefaultLanguage$1(); - } - return fetchDefaultLanguage; - }; - - const rLocale = /^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i; - class Locale { - constructor(sLocaleId) { - const aResult = rLocale.exec(sLocaleId.replace(/_/g, "-")); - if (aResult === null) { - throw new Error(`The given language ${sLocaleId} does not adhere to BCP-47.`); - } - this.sLocaleId = sLocaleId; - this.sLanguage = aResult[1] || DEFAULT_LANGUAGE; - this.sScript = aResult[2] || ""; - this.sRegion = aResult[3] || ""; - this.sVariant = (aResult[4] && aResult[4].slice(1)) || null; - this.sExtension = (aResult[5] && aResult[5].slice(1)) || null; - this.sPrivateUse = aResult[6] || null; - if (this.sLanguage) { - this.sLanguage = this.sLanguage.toLowerCase(); - } - if (this.sScript) { - this.sScript = this.sScript.toLowerCase().replace(/^[a-z]/, s => { - return s.toUpperCase(); - }); - } - if (this.sRegion) { - this.sRegion = this.sRegion.toUpperCase(); - } - } - getLanguage() { - return this.sLanguage; - } - getScript() { - return this.sScript; - } - getRegion() { - return this.sRegion; - } - getVariant() { - return this.sVariant; - } - getVariantSubtags() { - return this.sVariant ? this.sVariant.split("-") : []; - } - getExtension() { - return this.sExtension; - } - getExtensionSubtags() { - return this.sExtension ? this.sExtension.slice(2).split("-") : []; - } - getPrivateUse() { - return this.sPrivateUse; - } - getPrivateUseSubtags() { - return this.sPrivateUse ? this.sPrivateUse.slice(2).split("-") : []; - } - hasPrivateUseSubtag(sSubtag) { - return this.getPrivateUseSubtags().indexOf(sSubtag) >= 0; - } - toString() { - const r = [this.sLanguage]; - if (this.sScript) { - r.push(this.sScript); - } - if (this.sRegion) { - r.push(this.sRegion); - } - if (this.sVariant) { - r.push(this.sVariant); - } - if (this.sExtension) { - r.push(this.sExtension); - } - if (this.sPrivateUse) { - r.push(this.sPrivateUse); - } - return r.join("-"); - } - } - - const cache = new Map(); - const getLocaleInstance = (lang) => { - if (!cache.has(lang)) { - cache.set(lang, new Locale(lang)); - } - return cache.get(lang); - }; - const convertToLocaleOrNull = (lang) => { - try { - if (lang && typeof lang === "string") { - return getLocaleInstance(lang); - } - } - catch (e) { - // ignore - } - return new Locale(DEFAULT_LOCALE); - }; - /** - * Returns the locale based on the parameter or configured language Configuration#getLanguage - * If no language has been configured - a new locale based on browser language is returned - */ - const getLocale = (lang) => { - const configLanguage = getLanguage(); - if (configLanguage) { - return getLocaleInstance(configLanguage); - } - return convertToLocaleOrNull(detectNavigatorLanguage()); - }; - - const localeRegEX = /^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i; - const SAPSupportabilityLocales = /(?:^|-)(saptrc|sappsd)(?:-|$)/i; - /* Map for old language names for a few ISO639 codes. */ - const M_ISO639_NEW_TO_OLD = { - "he": "iw", - "yi": "ji", - "nb": "no", - "sr": "sh", - }; - /** - * Normalizes the given locale in BCP-47 syntax. - * @param {string} locale locale to normalize - * @returns {string} Normalized locale, "undefined" if the locale can't be normalized or the default locale, if no locale provided. - */ - const normalizeLocale = (locale) => { - let m; - if (!locale) { - return DEFAULT_LOCALE; - } - if (typeof locale === "string" && (m = localeRegEX.exec(locale.replace(/_/g, "-")))) { /* eslint-disable-line */ - let language = m[1].toLowerCase(); - let region = m[3] ? m[3].toUpperCase() : undefined; - const script = m[2] ? m[2].toLowerCase() : undefined; - const variants = m[4] ? m[4].slice(1) : undefined; - const isPrivate = m[6]; - language = M_ISO639_NEW_TO_OLD[language] || language; - // recognize and convert special SAP supportability locales (overwrites m[]!) - if ((isPrivate && (m = SAPSupportabilityLocales.exec(isPrivate))) /* eslint-disable-line */ || - (variants && (m = SAPSupportabilityLocales.exec(variants)))) { /* eslint-disable-line */ - return `en_US_${m[1].toLowerCase()}`; // for now enforce en_US (agreed with SAP SLS) - } - // Chinese: when no region but a script is specified, use default region for each script - if (language === "zh" && !region) { - if (script === "hans") { - region = "CN"; - } - else if (script === "hant") { - region = "TW"; - } - } - return language + (region ? "_" + region + (variants ? "_" + variants.replace("-", "_") : "") : ""); /* eslint-disable-line */ - } - return DEFAULT_LOCALE; - }; - - /** - * Calculates the next fallback locale for the given locale. - * - * @param {string} locale Locale string in Java format (underscores) or null - * @returns {string} Next fallback Locale or "en" if no fallbacks found. - */ - const nextFallbackLocale = (locale) => { - if (!locale) { - return DEFAULT_LOCALE; - } - if (locale === "zh_HK") { - return "zh_TW"; - } - // if there are multiple segments (separated by underscores), remove the last one - const p = locale.lastIndexOf("_"); - if (p >= 0) { - return locale.slice(0, p); - } - // for any language but the default, fallback to the default first before falling back to the 'raw' language (empty string) - return locale !== DEFAULT_LOCALE ? DEFAULT_LOCALE : ""; - }; - - // contains package names for which the warning has been shown - const warningShown$1 = new Set(); - const reportedErrors$1 = new Set(); - const bundleData = new Map(); - const bundlePromises = new Map(); - const loaders$2 = new Map(); - const _setI18nBundleData = (packageName, data) => { - bundleData.set(packageName, data); - }; - const getI18nBundleData = (packageName) => { - return bundleData.get(packageName); - }; - const _hasLoader = (packageName, localeId) => { - const bundleKey = `${packageName}/${localeId}`; - return loaders$2.has(bundleKey); - }; - // load bundle over the network once - const _loadMessageBundleOnce = (packageName, localeId) => { - const bundleKey = `${packageName}/${localeId}`; - const loadMessageBundle = loaders$2.get(bundleKey); - if (loadMessageBundle && !bundlePromises.get(bundleKey)) { - bundlePromises.set(bundleKey, loadMessageBundle(localeId)); - } - return bundlePromises.get(bundleKey); // Investigate if i18n loader exists and this won't return undefined. - }; - const _showAssetsWarningOnce$1 = (packageName) => { - if (!warningShown$1.has(packageName)) { - console.warn(`[${packageName}]: Message bundle assets are not configured. Falling back to English texts.`, /* eslint-disable-line */ ` Add \`import "${packageName}/dist/Assets.js"\` in your bundle and make sure your build tool supports dynamic imports and JSON imports. See section "Assets" in the documentation for more information.`); /* eslint-disable-line */ - warningShown$1.add(packageName); - } - }; - const useFallbackBundle = (packageName, localeId) => { - return localeId !== DEFAULT_LANGUAGE && !_hasLoader(packageName, localeId); - }; - /** - * This method preforms the asynchronous task of fetching the actual text resources. It will fetch - * each text resource over the network once (even for multiple calls to the same method). - * It should be fully finished before the i18nBundle class is created in the webcomponents. - * This method uses the bundle URLs that are populated by the `registerI18nBundle` method. - * To simplify the usage, the synchronization of both methods happens internally for the same `bundleId` - * @param {packageName} packageName the NPM package name - * @public - */ - const fetchI18nBundle = async (packageName) => { - const language = getLocale().getLanguage(); - const region = getLocale().getRegion(); - const variant = getLocale().getVariant(); - let localeId = language + (region ? `-${region}` : ``) + (variant ? `-${variant}` : ``); - if (useFallbackBundle(packageName, localeId)) { - localeId = normalizeLocale(localeId); - while (useFallbackBundle(packageName, localeId)) { - localeId = nextFallbackLocale(localeId); - } - } - // use default language unless configured to always fetch it from the network - const fetchDefaultLanguage = getFetchDefaultLanguage(); - if (localeId === DEFAULT_LANGUAGE && !fetchDefaultLanguage) { - _setI18nBundleData(packageName, null); // reset for the default language (if data was set for a previous language) - return; - } - if (!_hasLoader(packageName, localeId)) { - _showAssetsWarningOnce$1(packageName); - return; - } - try { - const data = await _loadMessageBundleOnce(packageName, localeId); - _setI18nBundleData(packageName, data); - } - catch (error) { - const e = error; - if (!reportedErrors$1.has(e.message)) { - reportedErrors$1.add(e.message); - console.error(e.message); /* eslint-disable-line */ - } - } - }; - // When the language changes dynamically (the user calls setLanguage), re-fetch all previously fetched bundles - attachLanguageChange((lang /* eslint-disable-line */) => { - const allPackages = [...bundleData.keys()]; - return Promise.all(allPackages.map(fetchI18nBundle)); - }); - - const messageFormatRegEX = /('')|'([^']+(?:''[^']*)*)(?:'|$)|\{([0-9]+(?:\s*,[^{}]*)?)\}|[{}]/g; - const formatMessage = (text, values) => { - values = values || []; - return text.replace(messageFormatRegEX, ($0, $1, $2, $3, offset) => { - if ($1) { - return '\''; /* eslint-disable-line */ - } - if ($2) { - return $2.replace(/''/g, '\''); /* eslint-disable-line */ - } - if ($3) { - const ind = typeof $3 === "string" ? parseInt($3) : $3; - return String(values[ind]); - } - throw new Error(`[i18n]: pattern syntax error at pos ${offset}`); - }); - }; - - const I18nBundleInstances = new Map(); - /** - * @class - * @public - */ - class I18nBundle { - constructor(packageName) { - this.packageName = packageName; - } - /** - * Returns a text in the currently loaded language - * - * @public - * @param textObj key/defaultText pair or just the key - * @param params Values for the placeholders - */ - getText(textObj, ...params) { - if (typeof textObj === "string") { - textObj = { key: textObj, defaultText: textObj }; - } - if (!textObj || !textObj.key) { - return ""; - } - const bundle = getI18nBundleData(this.packageName); - if (bundle && !bundle[textObj.key]) { - // eslint-disable-next-line no-console - console.warn(`Key ${textObj.key} not found in the i18n bundle, the default text will be used`); - } - const messageText = bundle && bundle[textObj.key] ? bundle[textObj.key] : (textObj.defaultText || textObj.key); - return formatMessage(messageText, params); - } - } - /** - * Returns the I18nBundle instance for the given package synchronously. - * - * @public - * @param packageName - */ - const getI18nBundleSync = (packageName) => { - if (I18nBundleInstances.has(packageName)) { - return I18nBundleInstances.get(packageName); - } - const i18nBundle = new I18nBundle(packageName); - I18nBundleInstances.set(packageName, i18nBundle); - return i18nBundle; - }; - /** - * Fetches and returns the I18nBundle instance for the given package. - * - * @public - * @param packageName - */ - const getI18nBundle = async (packageName) => { - await fetchI18nBundle(packageName); - return getI18nBundleSync(packageName); - }; - - const localeDataMap = new Map(); - const loaders$1 = new Map(); - const cldrPromises = new Map(); - const reportedErrors = new Set(); - let warningShown = false; - const M_ISO639_OLD_TO_NEW = { - "iw": "he", - "ji": "yi", - "in": "id", - }; - const _showAssetsWarningOnce = (localeId) => { - if (warningShown) { - return; - } - console.warn(`[LocaleData] Supported locale "${localeId}" not configured, import the "Assets.js" module from the webcomponents package you are using.`); /* eslint-disable-line */ - warningShown = true; - }; - const calcLocale = (language, region, script) => { - // normalize language and handle special cases - language = (language && M_ISO639_OLD_TO_NEW[language]) || language; - // Special case 1: in an SAP context, the inclusive language code "no" always means Norwegian Bokmal ("nb") - if (language === "no") { - language = "nb"; - } - // Special case 2: for Chinese, derive a default region from the script (this behavior is inherited from Java) - if (language === "zh" && !region) { - if (script === "Hans") { - region = "CN"; - } - else if (script === "Hant") { - region = "TW"; - } - } - // Special case 3: for Serbian, there are cyrillic and latin scripts, "sh" and "sr-latn" map to "latin", "sr" maps to cyrillic. - if (language === "sh" || (language === "sr" && script === "Latn")) { - language = "sr"; - region = "Latn"; - } - // try language + region - let localeId = `${language}_${region}`; - if (SUPPORTED_LOCALES.includes(localeId)) { - if (loaders$1.has(localeId)) { - // supported and has loader - return localeId; - } - // supported, no loader - fallback to default and warn - _showAssetsWarningOnce(localeId); - return DEFAULT_LOCALE; - } - // not supported, try language only - localeId = language; - if (SUPPORTED_LOCALES.includes(localeId)) { - if (loaders$1.has(localeId)) { - // supported and has loader - return localeId; - } - // supported, no loader - fallback to default and warn - _showAssetsWarningOnce(localeId); - return DEFAULT_LOCALE; - } - // not supported - fallback to default locale - return DEFAULT_LOCALE; - }; - // internal set data - const setLocaleData = (localeId, content) => { - localeDataMap.set(localeId, content); - }; - // load bundle over the network once - const _loadCldrOnce = (localeId) => { - if (!cldrPromises.get(localeId)) { - const loadCldr = loaders$1.get(localeId); - if (!loadCldr) { - throw new Error(`CLDR data for locale ${localeId} is not loaded!`); - } - cldrPromises.set(localeId, loadCldr(localeId)); - } - return cldrPromises.get(localeId); - }; - // external getAsync - const fetchCldr = async (language, region, script) => { - const localeId = calcLocale(language, region, script); - // reuse OpenUI5 CLDR if present - const openUI5Support = getFeature("OpenUI5Support"); - if (openUI5Support) { - const cldrContent = openUI5Support.getLocaleDataObject(); - if (cldrContent) { - // only if openui5 actually returned valid content - setLocaleData(localeId, cldrContent); - return; - } - } - // fetch it - try { - const cldrContent = await _loadCldrOnce(localeId); - setLocaleData(localeId, cldrContent); - } - catch (error) { - const e = error; - if (!reportedErrors.has(e.message)) { - reportedErrors.add(e.message); - console.error(e.message); /* eslint-disable-line */ - } - } - }; - const registerLocaleDataLoader = (localeId, loader) => { - loaders$1.set(localeId, loader); - }; - // register default loader for "en" from ui5 CDN (dev workflow without assets) - registerLocaleDataLoader("en", async () => { - const cldrContent = await fetch(`https://sdk.openui5.org/1.120.17/resources/sap/ui/core/cldr/en.json`); - return cldrContent.json(); - }); - // When the language changes dynamically (the user calls setLanguage), - // re-fetch the required CDRD data. - attachLanguageChange(() => { - const locale = getLocale(); - return fetchCldr(locale.getLanguage(), locale.getRegion(), locale.getScript()); - }); - - let autoId = 0; - const elementTimeouts = new Map(); - const uniqueDependenciesCache = new Map(); - const defaultConverter = { - fromAttribute(value, type) { - if (type === Boolean) { - return value !== null; - } - if (type === Number) { - return value === null ? undefined : parseFloat(value); - } - return value; - }, - toAttribute(value, type) { - if (type === Boolean) { - return value ? "" : null; - } - if (type === Object || type === Array) { - return null; - } - if (value === null || value === undefined) { - return null; - } - return String(value); - } - }; - function _invalidate(changeInfo) { - if (this._suppressInvalidation) { - return; - } - this.onInvalidation(changeInfo); - this._changedState.push(changeInfo); - renderDeferred(this); - this._invalidationEventProvider.fireEvent("invalidate", { - ...changeInfo, - target: this - }); - } - function getPropertyDescriptor(proto, name) { - do { - const descriptor = Object.getOwnPropertyDescriptor(proto, name); - if (descriptor) { - return descriptor; - } - proto = Object.getPrototypeOf(proto); - } while (proto && proto !== HTMLElement.prototype); - } - class UI5Element extends HTMLElement { - constructor() { - super(); - this._rendered = false; - const ctor = this.constructor; - this._changedState = []; - this._suppressInvalidation = true; - this._inDOM = false; - this._fullyConnected = false; - this._childChangeListeners = new Map(); - this._slotChangeListeners = new Map(); - this._invalidationEventProvider = new EventProvider(); - this._componentStateFinalizedEventProvider = new EventProvider(); - let deferredResolve; - this._domRefReadyPromise = new Promise(resolve => { - deferredResolve = resolve; - }); - this._domRefReadyPromise._deferredResolve = deferredResolve; - this._doNotSyncAttributes = new Set(); - this._slotsAssignedNodes = new WeakMap(); - this._state = { - ...ctor.getMetadata().getInitialState() - }; - this.initializedProperties = new Map(); - const allProps = this.constructor.getMetadata().getPropertiesList(); - allProps.forEach(propertyName => { - if (this.hasOwnProperty(propertyName)) { - const value = this[propertyName]; - this.initializedProperties.set(propertyName, value); - } - }); - this._internals = this.attachInternals(); - this._initShadowRoot(); - } - _initShadowRoot() { - const ctor = this.constructor; - if (ctor._needsShadowDOM()) { - const defaultOptions = { - mode: "open" - }; - this.attachShadow({ - ...defaultOptions, - ...ctor.getMetadata().getShadowRootOptions() - }); - const slotsAreManaged = ctor.getMetadata().slotsAreManaged(); - if (slotsAreManaged) { - this.shadowRoot.addEventListener("slotchange", this._onShadowRootSlotChange.bind(this)); - } - } - } - _onShadowRootSlotChange(e) { - const targetShadowRoot = e.target?.getRootNode(); - if (targetShadowRoot === this.shadowRoot) { - this._processChildren(); - } - } - get _id() { - if (!this.__id) { - this.__id = `ui5wc_${++autoId}`; - } - return this.__id; - } - render() { - const template = this.constructor.template; - return executeTemplate(template, this); - } - async connectedCallback() { - { - const rootNode = this.getRootNode(); - if (rootNode instanceof ShadowRoot && instanceOfUI5Element(rootNode.host)) { - const klass = rootNode.host.constructor; - const hasDependency = getTagsToScope(rootNode.host).includes(this.constructor.getMetadata().getPureTag()); - if (!hasDependency) { - console.error(`[UI5-FWK] ${this.constructor.getMetadata().getTag()} not found in dependencies of ${klass.getMetadata().getTag()}`); - } - } - } - { - const props = this.constructor.getMetadata().getProperties(); - for (const [prop, propData] of Object.entries(props)) { - if (Object.hasOwn(this, prop) && !this.initializedProperties.has(prop)) { - console.error(`[UI5-FWK] ${this.constructor.getMetadata().getTag()} has a property [${prop}] that is shadowed by the instance. Updates to this property will not invalidate the component. Possible reason is TS target ES2022 or TS useDefineForClassFields`); - } - } - } - const ctor = this.constructor; - this.setAttribute(ctor.getMetadata().getPureTag(), ""); - if (ctor.getMetadata().supportsF6FastNavigation()) { - this.setAttribute("data-sap-ui-fastnavgroup", "true"); - } - const slotsAreManaged = ctor.getMetadata().slotsAreManaged(); - this._inDOM = true; - if (slotsAreManaged) { - this._startObservingDOMChildren(); - await this._processChildren(); - } - if (!this._inDOM) { - return; - } - if (!ctor.asyncFinished) { - await ctor.definePromise; - } - renderImmediately(this); - this._domRefReadyPromise._deferredResolve(); - this._fullyConnected = true; - this.onEnterDOM(); - } - disconnectedCallback() { - const ctor = this.constructor; - const slotsAreManaged = ctor.getMetadata().slotsAreManaged(); - this._inDOM = false; - if (slotsAreManaged) { - this._stopObservingDOMChildren(); - } - if (this._fullyConnected) { - this.onExitDOM(); - this._fullyConnected = false; - } - this._domRefReadyPromise._deferredResolve(); - cancelRender(this); - } - onBeforeRendering() {} - onAfterRendering() {} - onEnterDOM() {} - onExitDOM() {} - _startObservingDOMChildren() { - const ctor = this.constructor; - const metadata = ctor.getMetadata(); - const shouldObserveChildren = metadata.hasSlots(); - if (!shouldObserveChildren) { - return; - } - const canSlotText = metadata.canSlotText(); - const mutationObserverOptions = { - childList: true, - subtree: canSlotText, - characterData: canSlotText - }; - observeDOMNode(this, this._processChildren.bind(this), mutationObserverOptions); - } - _stopObservingDOMChildren() { - unobserveDOMNode(this); - } - async _processChildren() { - const hasSlots = this.constructor.getMetadata().hasSlots(); - if (hasSlots) { - await this._updateSlots(); - } - } - async _updateSlots() { - const ctor = this.constructor; - const slotsMap = ctor.getMetadata().getSlots(); - const canSlotText = ctor.getMetadata().canSlotText(); - const domChildren = Array.from(canSlotText ? this.childNodes : this.children); - const slotsCachedContentMap = new Map(); - const propertyNameToSlotMap = new Map(); - for (const [slotName, slotData] of Object.entries(slotsMap)) { - const propertyName = slotData.propertyName || slotName; - propertyNameToSlotMap.set(propertyName, slotName); - slotsCachedContentMap.set(propertyName, [...this._state[propertyName]]); - this._clearSlot(slotName, slotData); - } - const autoIncrementMap = new Map(); - const slottedChildrenMap = new Map(); - const allChildrenUpgraded = domChildren.map(async (child, idx) => { - const slotName = getSlotName(child); - const slotData = slotsMap[slotName]; - if (slotData === undefined) { - if (slotName !== "default") { - const validValues = Object.keys(slotsMap).join(", "); - console.warn(`Unknown slotName: ${slotName}, ignoring`, child, `Valid values are: ${validValues}`); - } - return; - } - if (slotData.individualSlots) { - const nextIndex = (autoIncrementMap.get(slotName) || 0) + 1; - autoIncrementMap.set(slotName, nextIndex); - child._individualSlot = `${slotName}-${nextIndex}`; - } - if (child instanceof HTMLElement) { - const localName = child.localName; - const shouldWaitForCustomElement = localName.includes("-") && !shouldIgnoreCustomElement(localName); - if (shouldWaitForCustomElement) { - const isDefined = customElements.get(localName); - if (!isDefined) { - const whenDefinedPromise = customElements.whenDefined(localName); - let timeoutPromise = elementTimeouts.get(localName); - if (!timeoutPromise) { - timeoutPromise = new Promise(resolve => setTimeout(resolve, 1000)); - elementTimeouts.set(localName, timeoutPromise); - } - await Promise.race([whenDefinedPromise, timeoutPromise]); - } - customElements.upgrade(child); - } - } - child = ctor.getMetadata().constructor.validateSlotValue(child, slotData); - if (instanceOfUI5Element(child) && slotData.invalidateOnChildChange) { - const childChangeListener = this._getChildChangeListener(slotName); - child.attachInvalidate.call(child, childChangeListener); - } - if (child instanceof HTMLSlotElement) { - this._attachSlotChange(child, slotName, !!slotData.invalidateOnChildChange); - } - const propertyName = slotData.propertyName || slotName; - if (slottedChildrenMap.has(propertyName)) { - slottedChildrenMap.get(propertyName).push({ - child, - idx - }); - } else { - slottedChildrenMap.set(propertyName, [{ - child, - idx - }]); - } - }); - await Promise.all(allChildrenUpgraded); - slottedChildrenMap.forEach((children, propertyName) => { - this._state[propertyName] = children.sort((a, b) => a.idx - b.idx).map(_ => _.child); - this._state[kebabToCamelCase(propertyName)] = this._state[propertyName]; - }); - let invalidated = false; - for (const [slotName, slotData] of Object.entries(slotsMap)) { - const propertyName = slotData.propertyName || slotName; - if (!arraysAreEqual(slotsCachedContentMap.get(propertyName), this._state[propertyName])) { - _invalidate.call(this, { - type: "slot", - name: propertyNameToSlotMap.get(propertyName), - reason: "children" - }); - invalidated = true; - if (ctor.getMetadata().isFormAssociated()) { - setFormValue(this); - } - } - } - if (!invalidated) { - _invalidate.call(this, { - type: "slot", - name: "default", - reason: "textcontent" - }); - } - } - _clearSlot(slotName, slotData) { - const propertyName = slotData.propertyName || slotName; - const children = this._state[propertyName]; - children.forEach(child => { - if (instanceOfUI5Element(child)) { - const childChangeListener = this._getChildChangeListener(slotName); - child.detachInvalidate.call(child, childChangeListener); - } - if (child instanceof HTMLSlotElement) { - this._detachSlotChange(child, slotName); - } - }); - this._state[propertyName] = []; - this._state[kebabToCamelCase(propertyName)] = this._state[propertyName]; - } - attachInvalidate(callback) { - this._invalidationEventProvider.attachEvent("invalidate", callback); - } - detachInvalidate(callback) { - this._invalidationEventProvider.detachEvent("invalidate", callback); - } - _onChildChange(slotName, childChangeInfo) { - if (!this.constructor.getMetadata().shouldInvalidateOnChildChange(slotName, childChangeInfo.type, childChangeInfo.name)) { - return; - } - _invalidate.call(this, { - type: "slot", - name: slotName, - reason: "childchange", - child: childChangeInfo.target - }); - } - attributeChangedCallback(name, oldValue, newValue) { - let newPropertyValue; - if (this._doNotSyncAttributes.has(name)) { - return; - } - const properties = this.constructor.getMetadata().getProperties(); - const realName = name.replace(/^ui5-/, ""); - const nameInCamelCase = kebabToCamelCase(realName); - if (properties.hasOwnProperty(nameInCamelCase)) { - const propData = properties[nameInCamelCase]; - const converter = propData.converter ?? defaultConverter; - newPropertyValue = converter.fromAttribute(newValue, propData.type); - this[nameInCamelCase] = newPropertyValue; - } - } - formAssociatedCallback() { - const ctor = this.constructor; - if (!ctor.getMetadata().isFormAssociated()) { - return; - } - updateFormValue(this); - } - static get formAssociated() { - return this.getMetadata().isFormAssociated(); - } - _updateAttribute(name, newValue) { - const ctor = this.constructor; - if (!ctor.getMetadata().hasAttribute(name)) { - return; - } - const properties = ctor.getMetadata().getProperties(); - const propData = properties[name]; - const attrName = camelToKebabCase(name); - const converter = propData.converter || defaultConverter; - { - const tag = this.constructor.getMetadata().getTag(); - if (typeof newValue === "boolean" && propData.type !== Boolean) { - console.error(`[UI5-FWK] boolean value for property [${name}] of component [${tag}] is missing "{ type: Boolean }" in its property decorator. Attribute conversion will treat it as a string. If this is intended, pass the value converted to string, otherwise add the type to the property decorator`); - } - if (typeof newValue === "number" && propData.type !== Number) { - console.error(`[UI5-FWK] numeric value for property [${name}] of component [${tag}] is missing "{ type: Number }" in its property decorator. Attribute conversion will treat it as a string. If this is intended, pass the value converted to string, otherwise add the type to the property decorator`); - } - if (typeof newValue === "string" && propData.type && propData.type !== String) { - console.error(`[UI5-FWK] string value for property [${name}] of component [${tag}] which has a non-string type [${propData.type}] in its property decorator. Attribute conversion will stop and keep the string value in the property.`); - } - } - const newAttrValue = converter.toAttribute(newValue, propData.type); - this._doNotSyncAttributes.add(attrName); - if (newAttrValue === null || newAttrValue === undefined) { - this.removeAttribute(attrName); - } else { - this.setAttribute(attrName, newAttrValue); - } - this._doNotSyncAttributes.delete(attrName); - } - _getChildChangeListener(slotName) { - if (!this._childChangeListeners.has(slotName)) { - this._childChangeListeners.set(slotName, this._onChildChange.bind(this, slotName)); - } - return this._childChangeListeners.get(slotName); - } - _getSlotChangeListener(slotName) { - if (!this._slotChangeListeners.has(slotName)) { - this._slotChangeListeners.set(slotName, this._onSlotChange.bind(this, slotName)); - } - return this._slotChangeListeners.get(slotName); - } - _attachSlotChange(slot, slotName, invalidateOnChildChange) { - const slotChangeListener = this._getSlotChangeListener(slotName); - slot.addEventListener("slotchange", e => { - slotChangeListener.call(slot, e); - if (invalidateOnChildChange) { - const previousChildren = this._slotsAssignedNodes.get(slot); - if (previousChildren) { - previousChildren.forEach(child => { - if (instanceOfUI5Element(child)) { - const childChangeListener = this._getChildChangeListener(slotName); - child.detachInvalidate.call(child, childChangeListener); - } - }); - } - const newChildren = getSlottedNodesList([slot]); - this._slotsAssignedNodes.set(slot, newChildren); - newChildren.forEach(child => { - if (instanceOfUI5Element(child)) { - const childChangeListener = this._getChildChangeListener(slotName); - child.attachInvalidate.call(child, childChangeListener); - } - }); - } - }); - } - _detachSlotChange(child, slotName) { - child.removeEventListener("slotchange", this._getSlotChangeListener(slotName)); - } - _onSlotChange(slotName) { - _invalidate.call(this, { - type: "slot", - name: slotName, - reason: "slotchange" - }); - } - onInvalidation(changeInfo) {} - updateAttributes() { - const ctor = this.constructor; - const props = ctor.getMetadata().getProperties(); - for (const [prop, propData] of Object.entries(props)) { - this._updateAttribute(prop, this[prop]); - } - } - _render() { - const ctor = this.constructor; - const hasIndividualSlots = ctor.getMetadata().hasIndividualSlots(); - if (this.initializedProperties.size > 0) { - Array.from(this.initializedProperties.entries()).forEach(([prop, value]) => { - delete this[prop]; - this[prop] = value; - }); - this.initializedProperties.clear(); - } - this._suppressInvalidation = true; - try { - this.onBeforeRendering(); - if (!this._rendered) { - this.updateAttributes(); - } - this._componentStateFinalizedEventProvider.fireEvent("componentStateFinalized"); - } finally { - this._suppressInvalidation = false; - } - this._changedState = []; - if (ctor._needsShadowDOM()) { - updateShadowRoot(this); - } - this._rendered = true; - if (hasIndividualSlots) { - this._assignIndividualSlotsToChildren(); - } - this.onAfterRendering(); - } - _assignIndividualSlotsToChildren() { - const domChildren = Array.from(this.children); - domChildren.forEach(child => { - if (child._individualSlot) { - child.setAttribute("slot", child._individualSlot); - } - }); - } - _waitForDomRef() { - return this._domRefReadyPromise; - } - getDomRef() { - if (typeof this._getRealDomRef === "function") { - return this._getRealDomRef(); - } - if (!this.shadowRoot || this.shadowRoot.children.length === 0) { - return; - } - return this.shadowRoot.children[0]; - } - getFocusDomRef() { - const domRef = this.getDomRef(); - if (domRef) { - const focusRef = domRef.querySelector("[data-sap-focus-ref]"); - return focusRef || domRef; - } - } - async getFocusDomRefAsync() { - await this._waitForDomRef(); - return this.getFocusDomRef(); - } - async focus(focusOptions) { - await this._waitForDomRef(); - const focusDomRef = this.getFocusDomRef(); - if (focusDomRef === this) { - HTMLElement.prototype.focus.call(this, focusOptions); - } else if (focusDomRef && typeof focusDomRef.focus === "function") { - focusDomRef.focus(focusOptions); - } - } - fireEvent(name, data, cancelable = false, bubbles = true) { - const eventResult = this._fireEvent(name, data, cancelable, bubbles); - const pascalCaseEventName = kebabToPascalCase(name); - if (pascalCaseEventName !== name) { - return eventResult && this._fireEvent(pascalCaseEventName, data, cancelable, bubbles); - } - return eventResult; - } - fireDecoratorEvent(name, data) { - const eventData = this.getEventData(name); - const cancellable = eventData ? eventData.cancelable : false; - const bubbles = eventData ? eventData.bubbles : false; - const eventResult = this._fireEvent(name, data, cancellable, bubbles); - const pascalCaseEventName = kebabToPascalCase(name); - if (pascalCaseEventName !== name) { - return eventResult && this._fireEvent(pascalCaseEventName, data, cancellable, bubbles); - } - return eventResult; - } - _fireEvent(name, data, cancelable = false, bubbles = true) { - const noConflictEvent = new CustomEvent(`ui5-${name}`, { - detail: data, - composed: false, - bubbles, - cancelable - }); - const noConflictEventResult = this.dispatchEvent(noConflictEvent); - if (skipOriginalEvent(name)) { - return noConflictEventResult; - } - const normalEvent = new CustomEvent(name, { - detail: data, - composed: false, - bubbles, - cancelable - }); - const normalEventResult = this.dispatchEvent(normalEvent); - return normalEventResult && noConflictEventResult; - } - getEventData(name) { - const ctor = this.constructor; - const eventMap = ctor.getMetadata().getEvents(); - return eventMap[name]; - } - getSlottedNodes(slotName) { - return getSlottedNodesList(this[slotName]); - } - attachComponentStateFinalized(callback) { - this._componentStateFinalizedEventProvider.attachEvent("componentStateFinalized", callback); - } - detachComponentStateFinalized(callback) { - this._componentStateFinalizedEventProvider.detachEvent("componentStateFinalized", callback); - } - get effectiveDir() { - markAsRtlAware(this.constructor); - return getEffectiveDir(this); - } - get isUI5Element() { - return true; - } - get classes() { - return {}; - } - get accessibilityInfo() { - return {}; - } - static get observedAttributes() { - return this.getMetadata().getAttributesList(); - } - static _needsShadowDOM() { - return !!this.template || Object.prototype.hasOwnProperty.call(this.prototype, "render"); - } - static _generateAccessors() { - const proto = this.prototype; - const slotsAreManaged = this.getMetadata().slotsAreManaged(); - const properties = this.getMetadata().getProperties(); - for (const [prop, propData] of Object.entries(properties)) { - if (!isValidPropertyName(prop)) { - console.warn(`"${prop}" is not a valid property name. Use a name that does not collide with DOM APIs`); - } - const descriptor = getPropertyDescriptor(proto, prop); - let origSet; - if (descriptor?.set) { - origSet = descriptor.set; - } - let origGet; - if (descriptor?.get) { - origGet = descriptor.get; - } - Object.defineProperty(proto, prop, { - get() { - if (origGet) { - return origGet.call(this); - } - return this._state[prop]; - }, - set(value) { - const ctor = this.constructor; - const oldState = origGet ? origGet.call(this) : this._state[prop]; - const isDifferent = oldState !== value; - if (isDifferent) { - if (origSet) { - origSet.call(this, value); - } else { - this._state[prop] = value; - } - _invalidate.call(this, { - type: "property", - name: prop, - newValue: value, - oldValue: oldState - }); - if (this._rendered) { - this._updateAttribute(prop, value); - } - if (ctor.getMetadata().isFormAssociated()) { - setFormValue(this); - } - } - } - }); - } - if (slotsAreManaged) { - const slots = this.getMetadata().getSlots(); - for (const [slotName, slotData] of Object.entries(slots)) { - if (!isValidPropertyName(slotName)) { - console.warn(`"${slotName}" is not a valid property name. Use a name that does not collide with DOM APIs`); - } - const propertyName = slotData.propertyName || slotName; - const propertyDescriptor = { - get() { - if (this._state[propertyName] !== undefined) { - return this._state[propertyName]; - } - return []; - }, - set() { - throw new Error("Cannot set slot content directly, use the DOM APIs (appendChild, removeChild, etc...)"); - } - }; - Object.defineProperty(proto, propertyName, propertyDescriptor); - if (propertyName !== kebabToCamelCase(propertyName)) { - Object.defineProperty(proto, kebabToCamelCase(propertyName), propertyDescriptor); - } - } - } - } - static get dependencies() { - return []; - } - static cacheUniqueDependencies() { - const filtered = this.dependencies.filter((dep, index, deps) => deps.indexOf(dep) === index); - uniqueDependenciesCache.set(this, filtered); - } - static getUniqueDependencies() { - if (!uniqueDependenciesCache.has(this)) { - this.cacheUniqueDependencies(); - } - return uniqueDependenciesCache.get(this) || []; - } - static async onDefine() { - return Promise.resolve(); - } - static fetchI18nBundles() { - return Promise.all(Object.entries(this.getMetadata().getI18n()).map(pair => { - const {bundleName} = pair[1]; - return getI18nBundle(bundleName); - })); - } - static fetchCLDR() { - if (this.getMetadata().needsCLDR()) { - return fetchCldr(getLocale().getLanguage(), getLocale().getRegion(), getLocale().getScript()); - } - return Promise.resolve(); - } - static define() { - const defineSequence = async () => { - await boot(); - const result = await Promise.all([this.fetchI18nBundles(), this.fetchCLDR(), this.onDefine()]); - const [i18nBundles] = result; - Object.entries(this.getMetadata().getI18n()).forEach((pair, index) => { - const propertyName = pair[0]; - const targetClass = pair[1].target; - targetClass[propertyName] = i18nBundles[index]; - }); - this.asyncFinished = true; - }; - this.definePromise = defineSequence(); - const tag = this.getMetadata().getTag(); - const features = this.getMetadata().getFeatures(); - features.forEach(feature => { - if (getComponentFeature(feature)) { - this.cacheUniqueDependencies(); - } - subscribeForFeatureLoad(feature, this, this.cacheUniqueDependencies.bind(this)); - }); - const definedLocally = isTagRegistered(tag); - const definedGlobally = customElements.get(tag); - if (definedGlobally && !definedLocally) { - recordTagRegistrationFailure(tag); - } else if (!definedGlobally) { - this._generateAccessors(); - registerTag(tag); - customElements.define(tag, this); - } - return this; - } - static getMetadata() { - if (this.hasOwnProperty("_metadata")) { - return this._metadata; - } - const metadataObjects = [this.metadata]; - let klass = this; - while (klass !== UI5Element) { - klass = Object.getPrototypeOf(klass); - metadataObjects.unshift(klass.metadata); - } - const mergedMetadata = fnMerge({}, ...metadataObjects); - this._metadata = new UI5ElementMetadata(mergedMetadata); - return this._metadata; - } - get validity() { - return this._internals.validity; - } - get validationMessage() { - return this._internals.validationMessage; - } - checkValidity() { - return this._internals.checkValidity(); - } - reportValidity() { - return this._internals.reportValidity(); - } - } - UI5Element.metadata = {}; - UI5Element.styles = ""; - const instanceOfUI5Element = object => { - return ("isUI5Element" in object); - }; + const t$j=typeof document>"u",e$h={get userAgent(){return t$j?"":navigator.userAgent},get touch(){return t$j?!1:"ontouchstart"in window||navigator.maxTouchPoints>0},get chrome(){return t$j?!1:/(Chrome|CriOS)/.test(e$h.userAgent)},get firefox(){return t$j?!1:/Firefox/.test(e$h.userAgent)},get safari(){return t$j?!1:!e$h.chrome&&/(Version|PhantomJS)\/(\d+\.\d+).*Safari/.test(e$h.userAgent)},get webkit(){return t$j?!1:/webkit/.test(e$h.userAgent)},get windows(){return t$j?!1:navigator.platform.indexOf("Win")!==-1},get macOS(){return t$j?!1:!!navigator.userAgent.match(/Macintosh|Mac OS X/i)},get iOS(){return t$j?!1:!!navigator.platform.match(/iPhone|iPad|iPod/)||!!(e$h.userAgent.match(/Mac/)&&"ontouchend"in document)},get android(){return t$j?!1:!e$h.windows&&/Android/.test(e$h.userAgent)},get androidPhone(){return t$j?!1:e$h.android&&/(?=android)(?=.*mobile)/i.test(e$h.userAgent)},get ipad(){return t$j?!1:/ipad/i.test(e$h.userAgent)||/Macintosh/i.test(e$h.userAgent)&&"ontouchend"in document},_isPhone(){return u$f(),e$h.touch&&!r$i}};let o$l,i$m,r$i;const s$o=()=>{if(t$j||!e$h.windows)return !1;if(o$l===void 0){const n=e$h.userAgent.match(/Windows NT (\d+).(\d)/);o$l=n?parseFloat(n[1]):0;}return o$l>=8},c$k=()=>{if(t$j||!e$h.webkit)return !1;if(i$m===void 0){const n=e$h.userAgent.match(/(webkit)[ /]([\w.]+)/);i$m=n?parseFloat(n[1]):0;}return i$m>=537.1},u$f=()=>{if(t$j)return !1;if(r$i===void 0){if(e$h.ipad){r$i=!0;return}if(e$h.touch){if(s$o()){r$i=!0;return}if(e$h.chrome&&e$h.android){r$i=!/Mobile Safari\/[.0-9]+/.test(e$h.userAgent);return}let n=window.devicePixelRatio?window.devicePixelRatio:1;e$h.android&&c$k()&&(n=1),r$i=Math.min(window.screen.width/n,window.screen.height/n)>=600;return}r$i=e$h.userAgent.indexOf("Touch")!==-1||e$h.android&&!e$h.androidPhone;}},h$5=()=>e$h.safari,a$d=()=>(u$f(),(e$h.touch||s$o())&&r$i),d$b=()=>e$h._isPhone(),f$b=()=>t$j?!1:!a$d()&&!d$b()||s$o(),w$6=()=>e$h.iOS; - /** - * Returns a custom element class decorator. - * - * @param { string | object } tagNameOrComponentSettings - * @returns { ClassDecorator } - */ - const customElement = (tagNameOrComponentSettings = {}) => { - return (target) => { - if (!Object.prototype.hasOwnProperty.call(target, "metadata")) { - target.metadata = {}; - } - if (typeof tagNameOrComponentSettings === "string") { - target.metadata.tag = tagNameOrComponentSettings; - return; - } - const { tag, languageAware, themeAware, cldr, fastNavigation, formAssociated, shadowRootOptions, features, } = tagNameOrComponentSettings; - target.metadata.tag = tag; - if (languageAware) { - target.metadata.languageAware = languageAware; - } - if (cldr) { - target.metadata.cldr = cldr; - } - if (features) { - target.metadata.features = features; - } - if (themeAware) { - target.metadata.themeAware = themeAware; - } - if (fastNavigation) { - target.metadata.fastNavigation = fastNavigation; - } - if (formAssociated) { - target.metadata.formAssociated = formAssociated; - } - if (shadowRootOptions) { - target.metadata.shadowRootOptions = shadowRootOptions; - } - ["renderer", "template", "styles", "dependencies"].forEach((customElementEntity) => { - const customElementEntityValue = tagNameOrComponentSettings[customElementEntity]; - customElementEntityValue && Object.defineProperty(target, customElementEntity, { - get: () => tagNameOrComponentSettings[customElementEntity], - }); - }); - }; - }; + var c$j={},e$g=c$j.hasOwnProperty,a$c=c$j.toString,o$k=e$g.toString,l$h=o$k.call(Object),i$l=function(r){var t,n;return !r||a$c.call(r)!=="[object Object]"?!1:(t=Object.getPrototypeOf(r),t?(n=e$g.call(t,"constructor")&&t.constructor,typeof n=="function"&&o$k.call(n)===l$h):!0)}; - /** - * Returns a property decorator. - * - * @param { Property } propData - * @returns { PropertyDecorator } - */ - const property = (propData) => { - return (target, propertyKey) => { - const ctor = target.constructor; - if (!Object.prototype.hasOwnProperty.call(ctor, "metadata")) { - ctor.metadata = {}; - } - const metadata = ctor.metadata; - if (!metadata.properties) { - metadata.properties = {}; - } - const propsMetadata = metadata.properties; - if (!propsMetadata[propertyKey]) { - propsMetadata[propertyKey] = propData ?? {}; - } - }; + var c$i=Object.create(null),u$e=function(p,m,A,d){var n,t,e,a,o,i,r=arguments[2]||{},f=3,l=arguments.length,s=arguments[0]||!1,y=arguments[1]?void 0:c$i;for(typeof r!="object"&&typeof r!="function"&&(r={});fnew Promise(e=>{document.body?e():document.addEventListener("DOMContentLoaded",()=>{e();});}); + + let i$k = class i{constructor(){this._eventRegistry=new Map;}attachEvent(t,r){const n=this._eventRegistry,e=n.get(t);if(!Array.isArray(e)){n.set(t,[r]);return}e.includes(r)||e.push(r);}detachEvent(t,r){const n=this._eventRegistry,e=n.get(t);if(!e)return;const s=e.indexOf(r);s!==-1&&e.splice(s,1),e.length===0&&n.delete(t);}fireEvent(t,r){const e=this._eventRegistry.get(t);return e?e.map(s=>s.call(this,r)):[]}fireEventAsync(t,r){return Promise.all(this.fireEvent(t,r))}isHandlerAttached(t,r){const e=this._eventRegistry.get(t);return e?e.includes(r):!1}hasListeners(t){return !!this._eventRegistry.get(t)}}; + + const o$j=(t,n=document.body,r)=>{let e=document.querySelector(t);return e||(e=r?r():document.createElement(t),n.insertBefore(e,n.firstChild))}; + + const u$d=()=>{const t=document.createElement("meta");return t.setAttribute("name","ui5-shared-resources"),t.setAttribute("content",""),t},l$g=()=>typeof document>"u"?null:o$j('meta[name="ui5-shared-resources"]',document.head,u$d),m$d=(t,o)=>{const r=t.split(".");let e=l$g();if(!e)return o;for(let n=0;n { + (d$9.add(e), m$c.set(e, I$5())); + }, w$5 = e => d$9.has(e), $$3 = () => [...d$9.values()], y$7 = e => { + let n = m$c.get(e); + (n === void 0 && (n = g$8), s$n.has(n) || s$n.set(n, new Set()), s$n.get(n).add(e), c$h || (c$h = setTimeout(() => { + (R$3(), s$n = new Map(), c$h = void 0); + }, 1000))); + }, R$3 = () => { + const e = $$2(), n = I$5(), l = e[n]; + let t = "Multiple UI5 Web Components instances detected."; + (e.length > 1 && (t = `${t} +Loading order (versions before 1.1.0 not listed): ${e.map(i => ` +${i.description}`).join("")}`), [...s$n.keys()].forEach(i => { + let o, r; + i === g$8 ? (o = 1, r = { + description: "Older unknown runtime" + }) : (o = b$7(n, i), r = e[i]); + let a; + (o > 0 ? a = "an older" : o < 0 ? a = "a newer" : a = "the same", t = `${t} + +"${l.description}" failed to define ${s$n.get(i).size} tag(s) as they were defined by a runtime of ${a} version "${r.description}": ${[...s$n.get(i)].sort().join(", ")}.`, o > 0 ? t = `${t} +WARNING! If your code uses features of the above web components, unavailable in ${r.description}, it might not work as expected!` : t = `${t} +Since the above web components were defined by the same or newer version runtime, they should be compatible with your code.`); + }), t = `${t} + +To prevent other runtimes from defining tags that you use, consider using scoping or have third-party libraries use scoping: https://github.com/SAP/ui5-webcomponents/blob/main/docs/2-advanced/03-scoping.md.`, console.warn(t)); }; - /** - * Returns an event class decorator. - * - * @param { string } name the event name - * @param { EventData } data the event data - * @returns { ClassDecorator } - */ - const event = (name, data = {}) => { - return (target) => { - if (!Object.prototype.hasOwnProperty.call(target, "metadata")) { - target.metadata = {}; - } - const metadata = target.metadata; - if (!metadata.events) { - metadata.events = {}; - } - const eventsMetadata = metadata.events; - if (!eventsMetadata[name]) { - data.bubbles = !!data.bubbles; - data.cancelable = !!data.cancelable; - eventsMetadata[name] = data; - } - }; + const e$e={version:"2.5.0",major:2,minor:5,patch:0,suffix:"",isNext:!1,buildTime:1733409507}; + + let o$i,t$i={include:[/^ui5-/],exclude:[]};const s$m=new Map,c$g=()=>o$i,m$b=()=>t$i,i$j=e=>{if(!s$m.has(e)){const r=t$i.include.some(n=>e.match(n))&&!t$i.exclude.some(n=>e.match(n));s$m.set(e,r);}return s$m.get(e)},p$a=e=>{if(i$j(e))return c$g()}; + + let i$i,s$l="";const u$c=new Map,r$h=m$d("Runtimes",[]),x$1=()=>{if(i$i===void 0){i$i=r$h.length;const e=e$e;r$h.push({...e,get scopingSuffix(){return c$g()},get registeredTags(){return $$3()},get scopingRules(){return m$b()},alias:s$l,description:`Runtime ${i$i} - ver ${e.version}${""}`});}},I$5=()=>i$i,b$7=(e,m)=>{const o=`${e},${m}`;if(u$c.has(o))return u$c.get(o);const t=r$h[e],n=r$h[m];if(!t||!n)throw new Error("Invalid runtime index supplied");if(t.isNext||n.isNext)return t.buildTime-n.buildTime;const c=t.major-n.major;if(c)return c;const a=t.minor-n.minor;if(a)return a;const f=t.patch-n.patch;if(f)return f;const l=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}).compare(t.suffix,n.suffix);return u$c.set(o,l),l},$$2=()=>r$h; + + const l$f=typeof document>"u",o$h=(e,t)=>t?`${e}|${t}`:e,f$a=e=>e===void 0?!0:b$7(I$5(),parseInt(e))===1,u$b=(e,t,n="",s)=>{const i=typeof e=="string"?e:e.content,c=I$5(),r=new CSSStyleSheet;r.replaceSync(i),r._ui5StyleId=o$h(t,n),s&&(r._ui5RuntimeIndex=c,r._ui5Theme=s),document.adoptedStyleSheets=[...document.adoptedStyleSheets,r];},y$6=(e,t,n="",s)=>{const i=typeof e=="string"?e:e.content,c=I$5(),r=document.adoptedStyleSheets.find(d=>d._ui5StyleId===o$h(t,n));if(r)if(!s)r.replaceSync(i||"");else {const d=r._ui5RuntimeIndex;(r._ui5Theme!==s||f$a(d))&&(r.replaceSync(i||""),r._ui5RuntimeIndex=String(c),r._ui5Theme=s);}},S$5=(e,t="")=>l$f?!0:!!document.adoptedStyleSheets.find(n=>n._ui5StyleId===o$h(e,t)),p$9=(e,t="")=>{document.adoptedStyleSheets=document.adoptedStyleSheets.filter(n=>n._ui5StyleId!==o$h(e,t));},m$a=(e,t,n="",s)=>{S$5(t,n)?y$6(e,t,n,s):u$b(e,t,n,s);},R$2=(e,t)=>{if(e===void 0)return t;if(t===void 0)return e;const n=typeof t=="string"?t:t.content;return typeof e=="string"?`${e} ${n}`:{content:`${e.content} ${n}`,packageName:e.packageName,fileName:e.fileName}}; + + const s$k = new Map(), o$g = new Map(), i$h = new Map(), p$8 = "componentFeatureLoad", a$b = new i$k(), c$f = e => `${p$8}_${e}`, m$9 = e => s$k.get(e), F$1 = e => o$g.get(e), b$6 = (e, t, n) => { + const r = i$h.get(t); + r?.includes(e) || (r ? r.push(e) : i$h.set(t, [e]), a$b.attachEvent(c$f(e), n)); }; + const o$f={packageName:"@ui5/webcomponents-base",fileName:"FontFace.css",content:`@font-face{font-family:"72";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular.woff2?ui5-webcomponents) format("woff2"),local("72");unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular-full.woff2?ui5-webcomponents) format("woff2"),local('72-full')}@font-face{font-family:"72";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Bold';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Boldfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Light';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light.woff2?ui5-webcomponents) format("woff2"),local('72-Light');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Lightfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72Mono';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular.woff2?ui5-webcomponents) format('woff2'),local('72Mono');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Monofull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:'72Mono-Bold';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold.woff2?ui5-webcomponents) format('woff2'),local('72Mono-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Mono-Boldfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72Black";font-style:bold;font-weight:900;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black.woff2?ui5-webcomponents) format("woff2"),local('72Black');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Blackfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72-SemiboldDuplex";src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-SemiboldDuplex.woff2?ui5-webcomponents) format("woff2"),local('72-SemiboldDuplex');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}`}; + + const e$d={packageName:"@ui5/webcomponents-base",fileName:"OverrideFontFace.css",content:"@font-face{font-family:'72override';unicode-range:U+0102-0103,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EB7,U+1EB8-1EC7,U+1EC8-1ECB,U+1ECC-1EE3,U+1EE4-1EF1,U+1EF4-1EF7;src:local('Arial'),local('Helvetica'),local('sans-serif')}"}; + + const _$4={themes:{default:"sap_horizon",all:["sap_fiori_3","sap_fiori_3_dark","sap_fiori_3_hcb","sap_fiori_3_hcw","sap_horizon","sap_horizon_dark","sap_horizon_hcb","sap_horizon_hcw","sap_horizon_exp","sap_horizon_dark_exp","sap_horizon_hcb_exp","sap_horizon_hcw_exp"]},languages:{default:"en",all:["ar","bg","ca","cnr","cs","cy","da","de","el","en","en_GB","en_US_sappsd","en_US_saprigi","en_US_saptrc","es","es_MX","et","fi","fr","fr_CA","hi","hr","hu","in","it","iw","ja","kk","ko","lt","lv","mk","ms","nl","no","pl","pt_PT","pt","ro","ru","sh","sk","sl","sr","sv","th","tr","uk","vi","zh_CN","zh_TW"]},locales:{default:"en",all:["ar","ar_EG","ar_SA","bg","ca","cnr","cs","da","de","de_AT","de_CH","el","el_CY","en","en_AU","en_GB","en_HK","en_IE","en_IN","en_NZ","en_PG","en_SG","en_ZA","es","es_AR","es_BO","es_CL","es_CO","es_MX","es_PE","es_UY","es_VE","et","fa","fi","fr","fr_BE","fr_CA","fr_CH","fr_LU","he","hi","hr","hu","id","it","it_CH","ja","kk","ko","lt","lv","ms","mk","nb","nl","nl_BE","pl","pt","pt_PT","ro","ru","ru_UA","sk","sl","sr","sr_Latn","sv","th","tr","uk","vi","zh_CN","zh_HK","zh_SG","zh_TW"]}},e$c=_$4.themes.default,s$j=_$4.themes.all,a$a=_$4.languages.default,r$g=_$4.locales.default,n$j=_$4.locales.all; + + const o$e=typeof document>"u",n$i={search(){return o$e?"":window.location.search}},s$i=()=>o$e?"":window.location.href,u$a=()=>n$i.search(); + + const o$d=e=>{const t=document.querySelector(`META[name="${e}"]`);return t&&t.getAttribute("content")},s$h=e=>{const t=o$d("sap-allowedThemeOrigins");return t&&t.split(",").some(n=>n==="*"||e===n.trim())},a$9=(e,t)=>{const n=new URL(e).pathname;return new URL(n,t).toString()},g$7=e=>{let t;try{if(e.startsWith(".")||e.startsWith("/"))t=new URL(e,s$i()).toString();else {const n=new URL(e),r=n.origin;r&&s$h(r)?t=n.toString():t=a$9(n.toString(),s$i());}return t.endsWith("/")||(t=`${t}/`),`${t}UI5/`}catch{}}; + + var u$9=(l=>(l.Full="full",l.Basic="basic",l.Minimal="minimal",l.None="none",l))(u$9||{}); + + const e$b=new i$k,t$h="configurationReset",i$g=n=>{e$b.attachEvent(t$h,n);}; + + let p$7=!1,t$g={animationMode:u$9.Full,theme:e$c,themeRoot:void 0,rtl:void 0,language:void 0,timezone:void 0,calendarType:void 0,secondaryCalendarType:void 0,noConflict:!1,formatSettings:{},fetchDefaultLanguage:!1,defaultFontLoading:!0,enableDefaultTooltips:!0};const T$1=()=>(o$c(),t$g.theme),S$4=()=>(o$c(),t$g.themeRoot),L$2=()=>(o$c(),t$g.language),F=()=>(o$c(),t$g.fetchDefaultLanguage),U$2=()=>(o$c(),t$g.noConflict),b$5=()=>(o$c(),t$g.defaultFontLoading),i$f=new Map;i$f.set("true",!0),i$f.set("false",!1);const z$1=()=>{const n=document.querySelector("[data-ui5-config]")||document.querySelector("[data-id='sap-ui-config']");let e;if(n){try{e=JSON.parse(n.innerHTML);}catch{console.warn("Incorrect data-sap-ui-config format. Please use JSON");}e&&(t$g=e$f(t$g,e));}},E$3=()=>{const n=new URLSearchParams(u$a());n.forEach((e,a)=>{const r=a.split("sap-").length;r===0||r===a.split("sap-ui-").length||u$8(a,e,"sap");}),n.forEach((e,a)=>{a.startsWith("sap-ui")&&u$8(a,e,"sap-ui");});},P$4=n=>{const e=n.split("@")[1];return g$7(e)},w$4=(n,e)=>n==="theme"&&e.includes("@")?e.split("@")[0]:e,u$8=(n,e,a)=>{const r=e.toLowerCase(),s=n.split(`${a}-`)[1];i$f.has(e)&&(e=i$f.get(r)),s==="theme"?(t$g.theme=w$4(s,e),e&&e.includes("@")&&(t$g.themeRoot=P$4(e))):t$g[s]=e;},j$1=()=>{const n=m$9("OpenUI5Support");if(!n||!n.isOpenUI5Detected())return;const e=n.getConfigurationSettingsObject();t$g=e$f(t$g,e);},o$c=()=>{typeof document>"u"||p$7||(g$6(),p$7=!0);},g$6=n=>{z$1(),E$3(),j$1();}; + + let o$b;i$g(()=>{o$b=void 0;});const a$8=()=>(o$b===void 0&&(o$b=b$5()),o$b); + + const i$e=()=>{const t=m$9("OpenUI5Support");(!t||!t.isOpenUI5Detected())&&p$6(),c$e();},p$6=()=>{const t=document.querySelector("head>style[data-ui5-font-face]");!a$8()||t||S$5("data-ui5-font-face")||u$b(o$f,"data-ui5-font-face");},c$e=()=>{S$5("data-ui5-font-face-override")||u$b(e$d,"data-ui5-font-face-override");}; + + const t$f={packageName:"@ui5/webcomponents-base",fileName:"SystemCSSVars.css",content:":root{--_ui5_content_density:cozy}.sapUiSizeCompact,.ui5-content-density-compact,[data-ui5-compact-size]{--_ui5_content_density:compact}"}; + + const e$a=()=>{S$5("data-ui5-system-css-vars")||u$b(t$f,"data-ui5-system-css-vars");}; + + let l$e = class l{constructor(){this.list=[],this.lookup=new Set;}add(t){this.lookup.has(t)||(this.list.push(t),this.lookup.add(t));}remove(t){this.lookup.has(t)&&(this.list=this.list.filter(e=>e!==t),this.lookup.delete(t));}shift(){const t=this.list.shift();if(t)return this.lookup.delete(t),t}isEmpty(){return this.list.length===0}isAdded(t){return this.lookup.has(t)}process(t){let e;const s=new Map;for(e=this.shift();e;){const i=s.get(e)||0;if(i>10)throw new Error("Web component processed too many times this task, max allowed is: 10");t(e),s.set(e,i+1),e=this.shift();}}}; + + const t$e=new Set,n$h=e=>{t$e.add(e);},r$f=e=>t$e.has(e); + + const s$g=new Set,d$8=new i$k,n$g=new l$e;let t$d,a$7,m$8,i$d;const l$d=async e=>{n$g.add(e),await P$3();},c$d=e=>{d$8.fireEvent("beforeComponentRender",e),s$g.add(e),e._render();},h$3=e=>{n$g.remove(e),s$g.delete(e);},P$3=async()=>{i$d||(i$d=new Promise(e=>{window.requestAnimationFrame(()=>{n$g.process(c$d),i$d=null,e(),m$8||(m$8=setTimeout(()=>{m$8=void 0,n$g.isEmpty()&&U$1();},200));});})),await i$d;},y$5=()=>t$d||(t$d=new Promise(e=>{a$7=e,window.requestAnimationFrame(()=>{n$g.isEmpty()&&(t$d=void 0,e());});}),t$d),I$4=()=>{const e=$$3().map(r=>customElements.whenDefined(r));return Promise.all(e)},f$9=async()=>{await I$4(),await y$5();},U$1=()=>{n$g.isEmpty()&&a$7&&(a$7(),a$7=void 0,t$d=void 0);},C$2=async e=>{s$g.forEach(r=>{const o=r.constructor,u=o.getMetadata().getTag(),w=r$f(o),p=o.getMetadata().isLanguageAware(),E=o.getMetadata().isThemeAware();(!e||e.tag===u||e.rtlAware&&w||e.languageAware&&p||e.themeAware&&E)&&l$d(r);}),await f$9();}; + + const t$c=new i$k,r$e="themeRegistered",n$f=e=>{t$c.attachEvent(r$e,e);},s$f=e=>t$c.fireEvent(r$e,e); + + const y$4=new Map,h$2=new Map,S$3=new Map,u$7=new Set,i$c=new Set,f$8=(e,t,r)=>{h$2.set(`${e}/${t}`,r),u$7.add(e),i$c.add(t),s$f(t);},P$2=async(e,t,r)=>{const a=`${e}_${t}_${r||""}`,s=y$4.get(a);if(s!==void 0)return s;if(!i$c.has(t)){const c=[...i$c.values()].join(", ");return console.warn(`You have requested a non-registered theme ${t} - falling back to ${e$c}. Registered themes are: ${c}`),g$5(e,e$c)}const[o,d]=await Promise.all([g$5(e,t),r?g$5(e,r,!0):void 0]),n=R$2(o,d);return n&&y$4.set(a,n),n},g$5=async(e,t,r=!1)=>{const s=(r?S$3:h$2).get(`${e}/${t}`);if(!s){r||console.error(`Theme [${t}] not registered for package [${e}]`);return}let o;try{o=await s(t);}catch(n){console.error(e,n.message);return}return o._||o},$$1=()=>u$7,D$2=e=>i$c.has(e); + + const r$d=new Set,s$e=()=>{let e=document.querySelector(".sapThemeMetaData-Base-baseLib")||document.querySelector(".sapThemeMetaData-UI5-sap-ui-core");if(e)return getComputedStyle(e).backgroundImage;e=document.createElement("span"),e.style.display="none",e.classList.add("sapThemeMetaData-Base-baseLib"),document.body.appendChild(e);let t=getComputedStyle(e).backgroundImage;return t==="none"&&(e.classList.add("sapThemeMetaData-UI5-sap-ui-core"),t=getComputedStyle(e).backgroundImage),document.body.removeChild(e),t},o$a=e=>{const t=/\(["']?data:text\/plain;utf-8,(.*?)['"]?\)$/i.exec(e);if(t&&t.length>=2){let a=t[1];if(a=a.replace(/\\"/g,'"'),a.charAt(0)!=="{"&&a.charAt(a.length-1)!=="}")try{a=decodeURIComponent(a);}catch{r$d.has("decode")||(console.warn("Malformed theme metadata string, unable to decodeURIComponent"),r$d.add("decode"));return}try{return JSON.parse(a)}catch{r$d.has("parse")||(console.warn("Malformed theme metadata string, unable to parse JSON"),r$d.add("parse"));}}},d$7=e=>{let t,a;try{t=e.Path.match(/\.([^.]+)\.css_variables$/)[1],a=e.Extends[0];}catch{r$d.has("object")||(console.warn("Malformed theme metadata Object",e),r$d.add("object"));return}return {themeName:t,baseThemeName:a}},m$7=()=>{const e=s$e();if(!e||e==="none")return;const t=o$a(e);if(t)return d$7(t)}; + + const t$b=new i$k,d$6="themeLoaded",r$c=e=>t$b.fireEvent(d$6,e); + + const d$5=(r,n)=>{const e=document.createElement("link");return e.type="text/css",e.rel="stylesheet",n&&Object.entries(n).forEach(t=>e.setAttribute(...t)),e.href=r,document.head.appendChild(e),new Promise(t=>{e.addEventListener("load",t),e.addEventListener("error",t);})}; + + let t$a;i$g(()=>{t$a=void 0;});const n$e=()=>(t$a===void 0&&(t$a=S$4()),t$a),u$6=e=>`${n$e()}Base/baseLib/${e}/css_variables.css`,i$b=async e=>{const o=document.querySelector(`[sap-ui-webcomponents-theme="${e}"]`);o&&document.head.removeChild(o),await d$5(u$6(e),{"sap-ui-webcomponents-theme":e});}; + + const s$d="@ui5/webcomponents-theming",S$2=()=>$$1().has(s$d),P$1=async e=>{if(!S$2())return;const t=await P$2(s$d,e);t&&m$a(t,"data-ui5-theme-properties",s$d,e);},E$2=()=>{p$9("data-ui5-theme-properties",s$d);},U=async(e,t)=>{const o=[...$$1()].map(async a=>{if(a===s$d)return;const i=await P$2(a,e,t);i&&m$a(i,`data-ui5-component-properties-${I$5()}`,a);});return Promise.all(o)},w$3=async e=>{const t=m$7();if(t)return t;const r=m$9("OpenUI5Support");if(r&&r.isOpenUI5Detected()){if(r.cssVariablesLoaded())return {themeName:r.getConfigurationSettingsObject()?.theme,baseThemeName:""}}else if(n$e())return await i$b(e),m$7()},I$3=async e=>{const t=await w$3(e);!t||e!==t.themeName?await P$1(e):E$2();const r=D$2(e)?e:t&&t.baseThemeName;await U(r||e$c,t&&t.themeName===e?e:void 0),r$c(e);}; + + let t$9;i$g(()=>{t$9=void 0;});const r$b=()=>(t$9===void 0&&(t$9=T$1()),t$9),i$a=()=>{const e=r$b();return y$3(e)?!e.startsWith("sap_horizon"):!m$7()?.baseThemeName?.startsWith("sap_horizon")},y$3=e=>s$j.includes(e); + + let t$8=!1;const i$9=()=>{h$5()&&w$6()&&!t$8&&(document.body.addEventListener("touchstart",()=>{}),t$8=!0);}; + + let o$9=!1,r$a;const p$5=new i$k,l$c=async()=>{if(r$a!==void 0)return r$a;const e=async n=>{if(x$1(),typeof document>"u"){n();return}n$f(b$4);const t=m$9("OpenUI5Support"),f=t?t.isOpenUI5Detected():!1,s=m$9("F6Navigation");t&&await t.init(),s&&!f&&s.init(),await d$a(),await I$3(r$b()),t&&t.attachListeners(),i$e(),e$a(),i$9(),n(),o$9=!0,p$5.fireEvent("boot");};return r$a=new Promise(e),r$a},b$4=e=>{o$9&&e===r$b()&&I$3(r$b());}; + + const s$c=new Map,o$8=new Map,n$d=new Map,c$c=e=>{if(!s$c.has(e)){const a=p$4(e.split("-"));s$c.set(e,a);}return s$c.get(e)},l$b=e=>{if(!o$8.has(e)){const a=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();o$8.set(e,a);}return o$8.get(e)},p$4=e=>e.map((a,t)=>t===0?a.toLowerCase():a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(""),b$3=e=>{const a=n$d.get(e);if(a)return a;const t=c$c(e),r=t.charAt(0).toUpperCase()+t.slice(1);return n$d.set(e,r),r}; + + const o$7=t=>{if(!(t instanceof HTMLElement))return "default";const e=t.getAttribute("slot");if(e){const r=e.match(/^(.+?)-\d+$/);return r?r[1]:e}return "default"},n$c=t=>t instanceof HTMLSlotElement?t.assignedNodes({flatten:!0}).filter(e=>e instanceof HTMLElement):[t],s$b=t=>t.reduce((e,r)=>e.concat(n$c(r)),[]); + + let p$3 = class p{constructor(t){this.metadata=t;}getInitialState(){if(Object.prototype.hasOwnProperty.call(this,"_initialState"))return this._initialState;const t={};if(this.slotsAreManaged()){const o=this.getSlots();for(const[e,s]of Object.entries(o)){const n=s.propertyName||e;t[n]=[],t[c$c(n)]=t[n];}}return this._initialState=t,t}static validateSlotValue(t,a){return g$4(t,a)}getPureTag(){return this.metadata.tag||""}getFeatures(){return this.metadata.features||[]}getTag(){const t=this.metadata.tag;if(!t)return "";const a=p$a(t);return a?`${t}-${a}`:t}hasAttribute(t){const a=this.getProperties()[t];return a.type!==Object&&a.type!==Array&&!a.noAttribute}getPropertiesList(){return Object.keys(this.getProperties())}getAttributesList(){return this.getPropertiesList().filter(this.hasAttribute.bind(this)).map(l$b)}canSlotText(){return this.getSlots().default?.type===Node}hasSlots(){return !!Object.entries(this.getSlots()).length}hasIndividualSlots(){return this.slotsAreManaged()&&Object.values(this.getSlots()).some(t=>t.individualSlots)}slotsAreManaged(){return !!this.metadata.managedSlots}supportsF6FastNavigation(){return !!this.metadata.fastNavigation}getProperties(){return this.metadata.properties||(this.metadata.properties={}),this.metadata.properties}getEvents(){return this.metadata.events||(this.metadata.events={}),this.metadata.events}getSlots(){return this.metadata.slots||(this.metadata.slots={}),this.metadata.slots}isLanguageAware(){return !!this.metadata.languageAware}isThemeAware(){return !!this.metadata.themeAware}needsCLDR(){return !!this.metadata.cldr}getShadowRootOptions(){return this.metadata.shadowRootOptions||{}}isFormAssociated(){return !!this.metadata.formAssociated}shouldInvalidateOnChildChange(t,a,o){const e=this.getSlots()[t].invalidateOnChildChange;if(e===void 0)return !1;if(typeof e=="boolean")return e;if(typeof e=="object"){if(a==="property"){if(e.properties===void 0)return !1;if(typeof e.properties=="boolean")return e.properties;if(Array.isArray(e.properties))return e.properties.includes(o);throw new Error("Wrong format for invalidateOnChildChange.properties: boolean or array is expected")}if(a==="slot"){if(e.slots===void 0)return !1;if(typeof e.slots=="boolean")return e.slots;if(Array.isArray(e.slots))return e.slots.includes(o);throw new Error("Wrong format for invalidateOnChildChange.slots: boolean or array is expected")}}throw new Error("Wrong format for invalidateOnChildChange: boolean or object is expected")}getI18n(){return this.metadata.i18n||(this.metadata.i18n={}),this.metadata.i18n}};const g$4=(r,t)=>(r&&n$c(r).forEach(a=>{if(!(a instanceof t.type))throw new Error(`The element is not of type ${t.type.toString()}`)}),r); + + const r$9=()=>m$d("CustomStyle.eventProvider",new i$k),n$b="CustomCSSChange",i$8=t=>{r$9().attachEvent(n$b,t);},c$b=()=>m$d("CustomStyle.customCSSFor",{});i$8(t=>{C$2({tag:t});});const l$a=t=>{const e=c$b();return e[t]?e[t].join(""):""}; + + const a$6=t=>Array.isArray(t)?t.filter(r=>!!r).flat(10).map(r=>typeof r=="string"?r:r.content).join(" "):typeof t=="string"?t:t.content; + + const e$9=new Map;i$8(t=>{e$9.delete(`${t}_normal`);});const y$2=t=>{const o=t.getMetadata().getTag(),n=`${o}_normal`,s=m$9("OpenUI5Enablement");if(!e$9.has(n)){let l="";s&&(l=a$6(s.getBusyIndicatorStyles()));const a=l$a(o)||"",m=`${a$6(t.styles)} ${a} ${l}`;e$9.set(n,m);}return e$9.get(n)}; + + const e$8=new Map;i$8(t=>{e$8.delete(`${t}_normal`);});const s$a=t=>{const n=`${t.getMetadata().getTag()}_normal`;if(!e$8.has(n)){const a=y$2(t),o=new CSSStyleSheet;o.replaceSync(a),e$8.set(n,[o]);}return e$8.get(n)}; + + const n$a=o=>{const e=o.constructor,t=o.shadowRoot,r=o.render();if(!t){console.warn("There is no shadow root to update");return}t.adoptedStyleSheets=s$a(e),e.renderer(r,t,{host:o});}; + + const r$8=[],o$6=t=>r$8.some(s=>t.startsWith(s)); + + const t$7=new WeakMap,n$9=(e,o,r)=>{const s=new MutationObserver(o);t$7.set(e,s),s.observe(e,r);},b$2=e=>{const o=t$7.get(e);o&&(o.disconnect(),t$7.delete(e));}; + + const c$a=["value-changed","click"];let e$7;i$g(()=>{e$7=void 0;});const s$9=t=>c$a.includes(t),l$9=t=>{const n=o$5();return !(typeof n!="boolean"&&n.events&&n.events.includes&&n.events.includes(t))},o$5=()=>(e$7===void 0&&(e$7=U$2()),e$7),a$5=t=>{const n=o$5();return s$9(t)?!1:n===!0?!0:!l$9(t)}; + + const r$7=t=>t.matches(":dir(rtl)")?"rtl":"ltr"; + + const s$8=["disabled","title","hidden","role","draggable"],r$6=e=>s$8.includes(e)||e.startsWith("aria")?!0:![HTMLElement,Element,Node].some(t=>t.prototype.hasOwnProperty(e)); + + const n$8=(t,r)=>{if(t.length!==r.length)return !1;for(let e=0;e{const t=c$9(e),o=c$g();return n.call(e,e,t,o)},c$9=n=>{const e=n.constructor,t=e.getMetadata().getPureTag(),o=e.getUniqueDependencies().map(s=>s.getMetadata().getPureTag()).filter(i$j);return i$j(t)&&o.push(t),o}; + + const o$4=t=>{s$7(t)&&e$6(t);},e$6=t=>{if(t._internals?.form){if(n$7(t),!t.name){t._internals?.setFormValue(null);return}t._internals.setFormValue(t.formFormattedValue);}},n$7=async t=>{if(t._internals?.form)if(t.formValidity&&Object.keys(t.formValidity).some(r=>r)){const r=await t.formElementAnchor?.();t._internals.setValidity(t.formValidity,t.formValidityMessage,r);}else t._internals.setValidity({});},s$7=t=>"formFormattedValue"in t&&"name"in t; + + const t$6=typeof document>"u",o$3=()=>{if(t$6)return a$a;const a=navigator.languages,n=()=>navigator.language;return a&&a[0]||n()||a$a}; + + const e$5=new i$k,n$6="languageChange",t$5=a=>{e$5.attachEvent(n$6,a);}; + + let e$4,n$5;i$g(()=>{e$4=void 0,n$5=void 0;});const d$4=()=>(e$4===void 0&&(e$4=L$2()),e$4),c$8=()=>(n$5===void 0&&(n$5=F()),n$5); + + const n$4=/^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i;let r$5 = class r{constructor(s){const t=n$4.exec(s.replace(/_/g,"-"));if(t===null)throw new Error(`The given language ${s} does not adhere to BCP-47.`);this.sLocaleId=s,this.sLanguage=t[1]||a$a,this.sScript=t[2]||"",this.sRegion=t[3]||"",this.sVariant=t[4]&&t[4].slice(1)||null,this.sExtension=t[5]&&t[5].slice(1)||null,this.sPrivateUse=t[6]||null,this.sLanguage&&(this.sLanguage=this.sLanguage.toLowerCase()),this.sScript&&(this.sScript=this.sScript.toLowerCase().replace(/^[a-z]/,i=>i.toUpperCase())),this.sRegion&&(this.sRegion=this.sRegion.toUpperCase());}getLanguage(){return this.sLanguage}getScript(){return this.sScript}getRegion(){return this.sRegion}getVariant(){return this.sVariant}getVariantSubtags(){return this.sVariant?this.sVariant.split("-"):[]}getExtension(){return this.sExtension}getExtensionSubtags(){return this.sExtension?this.sExtension.slice(2).split("-"):[]}getPrivateUse(){return this.sPrivateUse}getPrivateUseSubtags(){return this.sPrivateUse?this.sPrivateUse.slice(2).split("-"):[]}hasPrivateUseSubtag(s){return this.getPrivateUseSubtags().indexOf(s)>=0}toString(){const s=[this.sLanguage];return this.sScript&&s.push(this.sScript),this.sRegion&&s.push(this.sRegion),this.sVariant&&s.push(this.sVariant),this.sExtension&&s.push(this.sExtension),this.sPrivateUse&&s.push(this.sPrivateUse),s.join("-")}}; + + const r$4=new Map,n$3=t=>(r$4.has(t)||r$4.set(t,new r$5(t)),r$4.get(t)),c$7=t=>{try{if(t&&typeof t=="string")return n$3(t)}catch{}return new r$5(r$g)},s$6=t=>{const e=d$4();return e?n$3(e):c$7(o$3())}; + + const _$3=/^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i,c$6=/(?:^|-)(saptrc|sappsd)(?:-|$)/i,f$7={he:"iw",yi:"ji",nb:"no",sr:"sh"},p$2=i=>{let e;if(!i)return r$g;if(typeof i=="string"&&(e=_$3.exec(i.replace(/_/g,"-")))){let t=e[1].toLowerCase(),n=e[3]?e[3].toUpperCase():void 0;const s=e[2]?e[2].toLowerCase():void 0,r=e[4]?e[4].slice(1):void 0,o=e[6];return t=f$7[t]||t,o&&(e=c$6.exec(o))||r&&(e=c$6.exec(r))?`en_US_${e[1].toLowerCase()}`:(t==="zh"&&!n&&(s==="hans"?n="CN":s==="hant"&&(n="TW")),t+(n?"_"+n+(r?"_"+r.replace("-","_"):""):""))}return r$g}; + + const e$3=r=>{if(!r)return r$g;if(r==="zh_HK")return "zh_TW";const n=r.lastIndexOf("_");return n>=0?r.slice(0,n):r!==r$g?r$g:""}; + + const d$3=new Set,m$6=new Set,g$3=new Map,l$7=new Map,u$5=new Map,f$6=(n,t)=>{g$3.set(n,t);},A$3=n=>g$3.get(n),h$1=(n,t)=>{const e=`${n}/${t}`;return u$5.has(e)},B$1=(n,t)=>{const e=`${n}/${t}`,r=u$5.get(e);return r&&!l$7.get(e)&&l$7.set(e,r(t)),l$7.get(e)},M$1=n=>{d$3.has(n)||(console.warn(`[${n}]: Message bundle assets are not configured. Falling back to English texts.`,` Add \`import "${n}/dist/Assets.js"\` in your bundle and make sure your build tool supports dynamic imports and JSON imports. See section "Assets" in the documentation for more information.`),d$3.add(n));},L$1=(n,t)=>t!==a$a&&!h$1(n,t),w$2=async n=>{const t=s$6().getLanguage(),e=s$6().getRegion(),r=s$6().getVariant();let s=t+(e?`-${e}`:"")+(r?`-${r}`:"");if(L$1(n,s))for(s=p$2(s);L$1(n,s);)s=e$3(s);const I=c$8();if(s===a$a&&!I){f$6(n,null);return}if(!h$1(n,s)){M$1(n);return}try{const o=await B$1(n,s);f$6(n,o);}catch(o){const a=o;m$6.has(a.message)||(m$6.add(a.message),console.error(a.message));}};t$5(n=>{const t=[...g$3.keys()];return Promise.all(t.map(w$2))}); + + const g$2=/('')|'([^']+(?:''[^']*)*)(?:'|$)|\{([0-9]+(?:\s*,[^{}]*)?)\}|[{}]/g,i$7=(n,t)=>(t=t||[],n.replace(g$2,(p,s,e,r,o)=>{if(s)return "'";if(e)return e.replace(/''/g,"'");if(r){const a=typeof r=="string"?parseInt(r):r;return String(t[a])}throw new Error(`[i18n]: pattern syntax error at pos ${o}`)})); + + const r$3=new Map;let u$4 = class u{constructor(e){this.packageName=e;}getText(e,...i){if(typeof e=="string"&&(e={key:e,defaultText:e}),!e||!e.key)return "";const t=A$3(this.packageName);t&&!t[e.key]&&console.warn(`Key ${e.key} not found in the i18n bundle, the default text will be used`);const l=t&&t[e.key]?t[e.key]:e.defaultText||e.key;return i$7(l,i)}};const a$4=n=>{if(r$3.has(n))return r$3.get(n);const e=new u$4(n);return r$3.set(n,e),e},f$5=async n=>(await w$2(n),a$4(n)); + + const f$4=new Map,s$5=new Map,i$6=new Map,D$1=new Set;let d$2=!1;const O$1={iw:"he",ji:"yi",in:"id"},l$6=t=>{d$2||(console.warn(`[LocaleData] Supported locale "${t}" not configured, import the "Assets.js" module from the webcomponents package you are using.`),d$2=!0);},R$1=(t,e,n)=>{t=t&&O$1[t]||t,t==="no"&&(t="nb"),t==="zh"&&!e&&(n==="Hans"?e="CN":n==="Hant"&&(e="TW")),(t==="sh"||t==="sr"&&n==="Latn")&&(t="sr",e="Latn");let r=`${t}_${e}`;return n$j.includes(r)?s$5.has(r)?r:(l$6(r),r$g):(r=t,n$j.includes(r)?s$5.has(r)?r:(l$6(r),r$g):r$g)},m$5=(t,e)=>{f$4.set(t,e);},_$2=t=>{if(!i$6.get(t)){const e=s$5.get(t);if(!e)throw new Error(`CLDR data for locale ${t} is not loaded!`);i$6.set(t,e(t));}return i$6.get(t)},u$3=async(t,e,n)=>{const r=R$1(t,e,n),p=m$9("OpenUI5Support");if(p){const o=p.getLocaleDataObject();if(o){m$5(r,o);return}}try{const o=await _$2(r);m$5(r,o);}catch(o){const c=o;D$1.has(c.message)||(D$1.add(c.message),console.error(c.message));}},C$1=(t,e)=>{s$5.set(t,e);};C$1("en",async()=>(await fetch("https://sdk.openui5.org/1.120.17/resources/sap/ui/core/cldr/en.json")).json()),t$5(()=>{const t=s$6();return u$3(t.getLanguage(),t.getRegion(),t.getScript())}); + + let it=0;const A$2=new Map,I$2=new Map,O={fromAttribute(d,u){return u===Boolean?d!==null:u===Number?d===null?void 0:parseFloat(d):d},toAttribute(d,u){return u===Boolean?d?"":null:u===Object||u===Array||d==null?null:String(d)}};function v$1(d){this._suppressInvalidation||(this.onInvalidation(d),this._changedState.push(d),l$d(this),this._invalidationEventProvider.fireEvent("invalidate",{...d,target:this}));}function at(d,u){do{const t=Object.getOwnPropertyDescriptor(d,u);if(t)return t;d=Object.getPrototypeOf(d);}while(d&&d!==HTMLElement.prototype)}let S$1 = class S extends HTMLElement{constructor(){super();this._rendered=!1;const t=this.constructor;this._changedState=[],this._suppressInvalidation=!0,this._inDOM=!1,this._fullyConnected=!1,this._childChangeListeners=new Map,this._slotChangeListeners=new Map,this._invalidationEventProvider=new i$k,this._componentStateFinalizedEventProvider=new i$k;let e;this._domRefReadyPromise=new Promise(n=>{e=n;}),this._domRefReadyPromise._deferredResolve=e,this._doNotSyncAttributes=new Set,this._slotsAssignedNodes=new WeakMap,this._state={...t.getMetadata().getInitialState()},this.initializedProperties=new Map,this.constructor.getMetadata().getPropertiesList().forEach(n=>{if(this.hasOwnProperty(n)){const o=this[n];this.initializedProperties.set(n,o);}}),this._internals=this.attachInternals(),this._initShadowRoot();}_initShadowRoot(){const t=this.constructor;if(t._needsShadowDOM()){const e={mode:"open"};this.attachShadow({...e,...t.getMetadata().getShadowRootOptions()}),t.getMetadata().slotsAreManaged()&&this.shadowRoot.addEventListener("slotchange",this._onShadowRootSlotChange.bind(this));}}_onShadowRootSlotChange(t){t.target?.getRootNode()===this.shadowRoot&&this._processChildren();}get _id(){return this.__id||(this.__id=`ui5wc_${++it}`),this.__id}render(){const t=this.constructor.template;return l$8(t,this)}async connectedCallback(){const t=this.constructor;this.setAttribute(t.getMetadata().getPureTag(),""),t.getMetadata().supportsF6FastNavigation()&&this.setAttribute("data-sap-ui-fastnavgroup","true");const e=t.getMetadata().slotsAreManaged();this._inDOM=!0,e&&(this._startObservingDOMChildren(),await this._processChildren()),this._inDOM&&(t.asyncFinished||await t.definePromise,c$d(this),this._domRefReadyPromise._deferredResolve(),this._fullyConnected=!0,this.onEnterDOM());}disconnectedCallback(){const e=this.constructor.getMetadata().slotsAreManaged();this._inDOM=!1,e&&this._stopObservingDOMChildren(),this._fullyConnected&&(this.onExitDOM(),this._fullyConnected=!1),this._domRefReadyPromise._deferredResolve(),h$3(this);}onBeforeRendering(){}onAfterRendering(){}onEnterDOM(){}onExitDOM(){}_startObservingDOMChildren(){const e=this.constructor.getMetadata();if(!e.hasSlots())return;const n=e.canSlotText(),o={childList:!0,subtree:n,characterData:n};n$9(this,this._processChildren.bind(this),o);}_stopObservingDOMChildren(){b$2(this);}async _processChildren(){this.constructor.getMetadata().hasSlots()&&await this._updateSlots();}async _updateSlots(){const t=this.constructor,e=t.getMetadata().getSlots(),s=t.getMetadata().canSlotText(),n=Array.from(s?this.childNodes:this.children),o=new Map,i=new Map;for(const[l,f]of Object.entries(e)){const c=f.propertyName||l;i.set(c,l),o.set(c,[...this._state[c]]),this._clearSlot(l,f);}const r=new Map,a=new Map,h=n.map(async(l,f)=>{const c=o$7(l),g=e[c];if(g===void 0){if(c!=="default"){const p=Object.keys(e).join(", ");console.warn(`Unknown slotName: ${c}, ignoring`,l,`Valid values are: ${p}`);}return}if(g.individualSlots){const p=(r.get(c)||0)+1;r.set(c,p),l._individualSlot=`${c}-${p}`;}if(l instanceof HTMLElement){const p=l.localName;if(p.includes("-")&&!o$6(p)){if(!customElements.get(p)){const T=customElements.whenDefined(p);let E=A$2.get(p);E||(E=new Promise(U=>setTimeout(U,1e3)),A$2.set(p,E)),await Promise.race([T,E]);}customElements.upgrade(l);}}if(l=t.getMetadata().constructor.validateSlotValue(l,g),_$1(l)&&g.invalidateOnChildChange){const p=this._getChildChangeListener(c);l.attachInvalidate.call(l,p);}l instanceof HTMLSlotElement&&this._attachSlotChange(l,c,!!g.invalidateOnChildChange);const C=g.propertyName||c;a.has(C)?a.get(C).push({child:l,idx:f}):a.set(C,[{child:l,idx:f}]);});await Promise.all(h),a.forEach((l,f)=>{this._state[f]=l.sort((c,g)=>c.idx-g.idx).map(c=>c.child),this._state[c$c(f)]=this._state[f];});let m=!1;for(const[l,f]of Object.entries(e)){const c=f.propertyName||l;n$8(o.get(c),this._state[c])||(v$1.call(this,{type:"slot",name:i.get(c),reason:"children"}),m=!0,t.getMetadata().isFormAssociated()&&e$6(this));}m||v$1.call(this,{type:"slot",name:"default",reason:"textcontent"});}_clearSlot(t,e){const s=e.propertyName||t;this._state[s].forEach(o=>{if(_$1(o)){const i=this._getChildChangeListener(t);o.detachInvalidate.call(o,i);}o instanceof HTMLSlotElement&&this._detachSlotChange(o,t);}),this._state[s]=[],this._state[c$c(s)]=this._state[s];}attachInvalidate(t){this._invalidationEventProvider.attachEvent("invalidate",t);}detachInvalidate(t){this._invalidationEventProvider.detachEvent("invalidate",t);}_onChildChange(t,e){this.constructor.getMetadata().shouldInvalidateOnChildChange(t,e.type,e.name)&&v$1.call(this,{type:"slot",name:t,reason:"childchange",child:e.target});}attributeChangedCallback(t,e,s){let n;if(this._doNotSyncAttributes.has(t))return;const o=this.constructor.getMetadata().getProperties(),i=t.replace(/^ui5-/,""),r=c$c(i);if(o.hasOwnProperty(r)){const a=o[r];n=(a.converter??O).fromAttribute(s,a.type),this[r]=n;}}formAssociatedCallback(){this.constructor.getMetadata().isFormAssociated()&&o$4(this);}static get formAssociated(){return this.getMetadata().isFormAssociated()}_updateAttribute(t,e){const s=this.constructor;if(!s.getMetadata().hasAttribute(t))return;const o=s.getMetadata().getProperties()[t],i=l$b(t),a=(o.converter||O).toAttribute(e,o.type);this._doNotSyncAttributes.add(i),a==null?this.removeAttribute(i):this.setAttribute(i,a),this._doNotSyncAttributes.delete(i);}_getChildChangeListener(t){return this._childChangeListeners.has(t)||this._childChangeListeners.set(t,this._onChildChange.bind(this,t)),this._childChangeListeners.get(t)}_getSlotChangeListener(t){return this._slotChangeListeners.has(t)||this._slotChangeListeners.set(t,this._onSlotChange.bind(this,t)),this._slotChangeListeners.get(t)}_attachSlotChange(t,e,s){const n=this._getSlotChangeListener(e);t.addEventListener("slotchange",o=>{if(n.call(t,o),s){const i=this._slotsAssignedNodes.get(t);i&&i.forEach(a=>{if(_$1(a)){const h=this._getChildChangeListener(e);a.detachInvalidate.call(a,h);}});const r=s$b([t]);this._slotsAssignedNodes.set(t,r),r.forEach(a=>{if(_$1(a)){const h=this._getChildChangeListener(e);a.attachInvalidate.call(a,h);}});}});}_detachSlotChange(t,e){t.removeEventListener("slotchange",this._getSlotChangeListener(e));}_onSlotChange(t){v$1.call(this,{type:"slot",name:t,reason:"slotchange"});}onInvalidation(t){}updateAttributes(){const e=this.constructor.getMetadata().getProperties();for(const[s,n]of Object.entries(e))this._updateAttribute(s,this[s]);}_render(){const t=this.constructor,e=t.getMetadata().hasIndividualSlots();this.initializedProperties.size>0&&(Array.from(this.initializedProperties.entries()).forEach(([s,n])=>{delete this[s],this[s]=n;}),this.initializedProperties.clear()),this._suppressInvalidation=!0;try{this.onBeforeRendering(),this._rendered||this.updateAttributes(),this._componentStateFinalizedEventProvider.fireEvent("componentStateFinalized");}finally{this._suppressInvalidation=!1;}this._changedState=[],t._needsShadowDOM()&&n$a(this),this._rendered=!0,e&&this._assignIndividualSlotsToChildren(),this.onAfterRendering();}_assignIndividualSlotsToChildren(){Array.from(this.children).forEach(e=>{e._individualSlot&&e.setAttribute("slot",e._individualSlot);});}_waitForDomRef(){return this._domRefReadyPromise}getDomRef(){if(typeof this._getRealDomRef=="function")return this._getRealDomRef();if(!(!this.shadowRoot||this.shadowRoot.children.length===0))return this.shadowRoot.children[0]}getFocusDomRef(){const t=this.getDomRef();if(t)return t.querySelector("[data-sap-focus-ref]")||t}async getFocusDomRefAsync(){return await this._waitForDomRef(),this.getFocusDomRef()}async focus(t){await this._waitForDomRef();const e=this.getFocusDomRef();e===this?HTMLElement.prototype.focus.call(this,t):e&&typeof e.focus=="function"&&e.focus(t);}fireEvent(t,e,s=!1,n=!0){const o=this._fireEvent(t,e,s,n),i=b$3(t);return i!==t?o&&this._fireEvent(i,e,s,n):o}fireDecoratorEvent(t,e){const s=this.getEventData(t),n=s?s.cancelable:!1,o=s?s.bubbles:!1,i=this._fireEvent(t,e,n,o),r=b$3(t);return r!==t?i&&this._fireEvent(r,e,n,o):i}_fireEvent(t,e,s=!1,n=!0){const o=new CustomEvent(`ui5-${t}`,{detail:e,composed:!1,bubbles:n,cancelable:s}),i=this.dispatchEvent(o);if(a$5(t))return i;const r=new CustomEvent(t,{detail:e,composed:!1,bubbles:n,cancelable:s});return this.dispatchEvent(r)&&i}getEventData(t){return this.constructor.getMetadata().getEvents()[t]}getSlottedNodes(t){return s$b(this[t])}attachComponentStateFinalized(t){this._componentStateFinalizedEventProvider.attachEvent("componentStateFinalized",t);}detachComponentStateFinalized(t){this._componentStateFinalizedEventProvider.detachEvent("componentStateFinalized",t);}get effectiveDir(){return n$h(this.constructor),r$7(this)}get isUI5Element(){return !0}get classes(){return {}}get accessibilityInfo(){return {}}static get observedAttributes(){return this.getMetadata().getAttributesList()}static _needsShadowDOM(){return !!this.template||Object.prototype.hasOwnProperty.call(this.prototype,"render")}static _generateAccessors(){const t=this.prototype,e=this.getMetadata().slotsAreManaged(),s=this.getMetadata().getProperties();for(const[n,o]of Object.entries(s)){r$6(n)||console.warn(`"${n}" is not a valid property name. Use a name that does not collide with DOM APIs`);const i=at(t,n);let r;i?.set&&(r=i.set);let a;i?.get&&(a=i.get),Object.defineProperty(t,n,{get(){return a?a.call(this):this._state[n]},set(h){const m=this.constructor,l=a?a.call(this):this._state[n];l!==h&&(r?r.call(this,h):this._state[n]=h,v$1.call(this,{type:"property",name:n,newValue:h,oldValue:l}),this._rendered&&this._updateAttribute(n,h),m.getMetadata().isFormAssociated()&&e$6(this));}});}if(e){const n=this.getMetadata().getSlots();for(const[o,i]of Object.entries(n)){r$6(o)||console.warn(`"${o}" is not a valid property name. Use a name that does not collide with DOM APIs`);const r=i.propertyName||o,a={get(){return this._state[r]!==void 0?this._state[r]:[]},set(){throw new Error("Cannot set slot content directly, use the DOM APIs (appendChild, removeChild, etc...)")}};Object.defineProperty(t,r,a),r!==c$c(r)&&Object.defineProperty(t,c$c(r),a);}}}static{this.metadata={};}static{this.styles="";}static get dependencies(){return []}static cacheUniqueDependencies(){const t=this.dependencies.filter((e,s,n)=>n.indexOf(e)===s);I$2.set(this,t);}static getUniqueDependencies(){return I$2.has(this)||this.cacheUniqueDependencies(),I$2.get(this)||[]}static async onDefine(){return Promise.resolve()}static fetchI18nBundles(){return Promise.all(Object.entries(this.getMetadata().getI18n()).map(t=>{const{bundleName:e}=t[1];return f$5(e)}))}static fetchCLDR(){return this.getMetadata().needsCLDR()?u$3(s$6().getLanguage(),s$6().getRegion(),s$6().getScript()):Promise.resolve()}static define(){const t=async()=>{await l$c();const i=await Promise.all([this.fetchI18nBundles(),this.fetchCLDR(),this.onDefine()]),[r]=i;Object.entries(this.getMetadata().getI18n()).forEach((a,h)=>{const m=a[0],l=a[1].target;l[m]=r[h];}),this.asyncFinished=!0;};this.definePromise=t();const e=this.getMetadata().getTag();this.getMetadata().getFeatures().forEach(i=>{F$1(i)&&this.cacheUniqueDependencies(),b$6(i,this,this.cacheUniqueDependencies.bind(this));});const n=w$5(e),o=customElements.get(e);return o&&!n?y$7(e):o||(this._generateAccessors(),h$4(e),customElements.define(e,this)),this}static getMetadata(){if(this.hasOwnProperty("_metadata"))return this._metadata;const t=[this.metadata];let e=this;for(;e!==S;)e=Object.getPrototypeOf(e),t.unshift(e.metadata);const s=e$f({},...t);return this._metadata=new p$3(s),this._metadata}get validity(){return this._internals.validity}get validationMessage(){return this._internals.validationMessage}checkValidity(){return this._internals.checkValidity()}reportValidity(){return this._internals.reportValidity()}};const _$1=d=>"isUI5Element"in d; + + const m$4=(a={})=>e=>{if(Object.prototype.hasOwnProperty.call(e,"metadata")||(e.metadata={}),typeof a=="string"){e.metadata.tag=a;return}const{tag:f,languageAware:o,themeAware:r,cldr:s,fastNavigation:l,formAssociated:n,shadowRootOptions:d,features:i}=a;e.metadata.tag=f,o&&(e.metadata.languageAware=o),s&&(e.metadata.cldr=s),i&&(e.metadata.features=i),r&&(e.metadata.themeAware=r),l&&(e.metadata.fastNavigation=l),n&&(e.metadata.formAssociated=n),d&&(e.metadata.shadowRootOptions=d),["renderer","template","styles","dependencies"].forEach(t=>{a[t]&&Object.defineProperty(e,t,{get:()=>a[t]});});}; + + const s$4=o=>(p,r)=>{const t=p.constructor;Object.prototype.hasOwnProperty.call(t,"metadata")||(t.metadata={});const e=t.metadata;e.properties||(e.properties={});const a=e.properties;a[r]||(a[r]=o??{});}; + + const l$5=(s,e={})=>t=>{Object.prototype.hasOwnProperty.call(t,"metadata")||(t.metadata={});const n=t.metadata;n.events||(n.events={});const a=n.events;a[s]||(e.bubbles=!!e.bubbles,e.cancelable=!!e.cancelable,a[s]=e);}; + /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - var t$1;const i$1=window,s$1=i$1.trustedTypes,e$2=s$1?s$1.createPolicy("lit-html",{createHTML:t=>t}):void 0,o$1="$lit$",n=`lit$${(Math.random()+"").slice(9)}$`,l$2="?"+n,h=`<${l$2}>`,r$1=document,u$1=()=>r$1.createComment(""),d=t=>null===t||"object"!=typeof t&&"function"!=typeof t,c$2=Array.isArray,v=t=>c$2(t)||"function"==typeof(null==t?void 0:t[Symbol.iterator]),a$1="[ \t\n\f\r]",f$1=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,_=/-->/g,m$1=/>/g,p$1=RegExp(`>|${a$1}(?:([^\\s"'>=/]+)(${a$1}*=${a$1}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),g=/'/g,$=/"/g,y=/^(?:script|style|textarea|title)$/i,w=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),x=w(1),b=w(2),T=Symbol.for("lit-noChange"),A=Symbol.for("lit-nothing"),E=new WeakMap,C=r$1.createTreeWalker(r$1,129,null,!1);function P(t,i){if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==e$2?e$2.createHTML(i):i}const V=(t,i)=>{const s=t.length-1,e=[];let l,r=2===i?"":"",u=f$1;for(let i=0;i"===c[0]?(u=null!=l?l:f$1,v=-1):void 0===c[1]?v=-2:(v=u.lastIndex-c[2].length,d=c[1],u=void 0===c[3]?p$1:'"'===c[3]?$:g):u===$||u===g?u=p$1:u===_||u===m$1?u=f$1:(u=p$1,l=void 0);const w=u===p$1&&t[i+1].startsWith("/>")?" ":"";r+=u===f$1?s+h:v>=0?(e.push(d),s.slice(0,v)+o$1+s.slice(v)+n+w):s+n+(-2===v?(e.push(void 0),i):w);}return [P(t,r+(t[s]||"")+(2===i?"":"")),e]};class N{constructor({strings:t,_$litType$:i},e){let h;this.parts=[];let r=0,d=0;const c=t.length-1,v=this.parts,[a,f]=V(t,i);if(this.el=N.createElement(a,e),C.currentNode=this.el.content,2===i){const t=this.el.content,i=t.firstChild;i.remove(),t.append(...i.childNodes);}for(;null!==(h=C.nextNode())&&v.length0){h.textContent=s$1?s$1.emptyScript:"";for(let s=0;s2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=A;}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,i=this,s,e){const o=this.strings;let n=!1;if(void 0===o)t=S(this,t,i,0),n=!d(t)||t!==this._$AH&&t!==T,n&&(this._$AH=t);else {const e=t;let l,h;for(t=o[0],l=0;l{var e,o;const n=null!==(e=null==s?void 0:s.renderBefore)&&void 0!==e?e:i;let l=n._$litPart$;if(void 0===l){const t=null!==(o=null==s?void 0:s.renderBefore)&&void 0!==o?o:null;n._$litPart$=l=new R(i.insertBefore(u$1(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; + var t$4;const i$5=window,s$3=i$5.trustedTypes,e$2=s$3?s$3.createPolicy("lit-html",{createHTML:t=>t}):void 0,o$2="$lit$",n$2=`lit$${(Math.random()+"").slice(9)}$`,l$4="?"+n$2,h=`<${l$4}>`,r$2=document,u$2=()=>r$2.createComment(""),d$1=t=>null===t||"object"!=typeof t&&"function"!=typeof t,c$5=Array.isArray,v=t=>c$5(t)||"function"==typeof(null==t?void 0:t[Symbol.iterator]),a$3="[ \t\n\f\r]",f$3=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,_=/-->/g,m$3=/>/g,p$1=RegExp(`>|${a$3}(?:([^\\s"'>=/]+)(${a$3}*=${a$3}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),g$1=/'/g,$=/"/g,y$1=/^(?:script|style|textarea|title)$/i,w$1=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),x=w$1(1),b$1=w$1(2),T=Symbol.for("lit-noChange"),A$1=Symbol.for("lit-nothing"),E$1=new WeakMap,C=r$2.createTreeWalker(r$2,129,null,!1);function P(t,i){if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==e$2?e$2.createHTML(i):i}const V=(t,i)=>{const s=t.length-1,e=[];let l,r=2===i?"":"",u=f$3;for(let i=0;i"===c[0]?(u=null!=l?l:f$3,v=-1):void 0===c[1]?v=-2:(v=u.lastIndex-c[2].length,d=c[1],u=void 0===c[3]?p$1:'"'===c[3]?$:g$1):u===$||u===g$1?u=p$1:u===_||u===m$3?u=f$3:(u=p$1,l=void 0);const w=u===p$1&&t[i+1].startsWith("/>")?" ":"";r+=u===f$3?s+h:v>=0?(e.push(d),s.slice(0,v)+o$2+s.slice(v)+n$2+w):s+n$2+(-2===v?(e.push(void 0),i):w);}return [P(t,r+(t[s]||"")+(2===i?"":"")),e]};let N$1 = class N{constructor({strings:t,_$litType$:i},e){let h;this.parts=[];let r=0,d=0;const c=t.length-1,v=this.parts,[a,f]=V(t,i);if(this.el=N.createElement(a,e),C.currentNode=this.el.content,2===i){const t=this.el.content,i=t.firstChild;i.remove(),t.append(...i.childNodes);}for(;null!==(h=C.nextNode())&&v.length0){h.textContent=s$3?s$3.emptyScript:"";for(let s=0;s2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=A$1;}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,i=this,s,e){const o=this.strings;let n=!1;if(void 0===o)t=S(this,t,i,0),n=!d$1(t)||t!==this._$AH&&t!==T,n&&(this._$AH=t);else {const e=t;let l,h;for(t=o[0],l=0;l{var e,o;const n=null!==(e=null==s?void 0:s.renderBefore)&&void 0!==e?e:i;let l=n._$litPart$;if(void 0===l){const t=null!==(o=null==s?void 0:s.renderBefore)&&void 0!==o?o:null;n._$litPart$=l=new R(i.insertBefore(u$2(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - const t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e$1=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i;}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}} + const t$3={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e$1=t=>(...e)=>({_$litDirective$:t,values:e});let i$4 = class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i;}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}; /** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const {I:l$1}=j,r=()=>document.createComment(""),c$1=(o,i,n)=>{var t;const v=o._$AA.parentNode,d=void 0===i?o._$AB:i._$AA;if(void 0===n){const i=v.insertBefore(r(),d),t=v.insertBefore(r(),d);n=new l$1(i,t,o,o.options);}else {const l=n._$AB.nextSibling,i=n._$AM,u=i!==o;if(u){let l;null===(t=n._$AQ)||void 0===t||t.call(n,o),n._$AM=o,void 0!==n._$AP&&(l=o._$AU)!==i._$AU&&n._$AP(l);}if(l!==d||u){let o=n._$AA;for(;o!==l;){const l=o.nextSibling;v.insertBefore(o,d),o=l;}}}return n},f=(o,l,i=o)=>(o._$AI(l,i),o),s={},a=(o,l=s)=>o._$AH=l,m=o=>o._$AH,p=o=>{var l;null===(l=o._$AP)||void 0===l||l.call(o,!1,!0);let i=o._$AA;const n=o._$AB.nextSibling;for(;i!==n;){const o=i.nextSibling;i.remove(),i=o;}}; + */const {I:l$3}=j,r$1=()=>document.createComment(""),c$4=(o,i,n)=>{var t;const v=o._$AA.parentNode,d=void 0===i?o._$AB:i._$AA;if(void 0===n){const i=v.insertBefore(r$1(),d),t=v.insertBefore(r$1(),d);n=new l$3(i,t,o,o.options);}else {const l=n._$AB.nextSibling,i=n._$AM,u=i!==o;if(u){let l;null===(t=n._$AQ)||void 0===t||t.call(n,o),n._$AM=o,void 0!==n._$AP&&(l=o._$AU)!==i._$AU&&n._$AP(l);}if(l!==d||u){let o=n._$AA;for(;o!==l;){const l=o.nextSibling;v.insertBefore(o,d),o=l;}}}return n},f$2=(o,l,i=o)=>(o._$AI(l,i),o),s$2={},a$2=(o,l=s$2)=>o._$AH=l,m$2=o=>o._$AH,p=o=>{var l;null===(l=o._$AP)||void 0===l||l.call(o,!1,!0);let i=o._$AA;const n=o._$AB.nextSibling;for(;i!==n;){const o=i.nextSibling;i.remove(),i=o;}}; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - const u=(e,s,t)=>{const r=new Map;for(let l=s;l<=t;l++)r.set(e[l],l);return r},c=e$1(class extends i{constructor(e){if(super(e),e.type!==t.CHILD)throw Error("repeat() can only be used in text expressions")}ct(e,s,t){let r;void 0===t?t=s:void 0!==s&&(r=s);const l=[],o=[];let i=0;for(const s of e)l[i]=r?r(s,i):i,o[i]=t(s,i),i++;return {values:o,keys:l}}render(e,s,t){return this.ct(e,s,t).values}update(s,[t,r,c]){var d;const a$1=m(s),{values:p$1,keys:v}=this.ct(t,r,c);if(!Array.isArray(a$1))return this.ut=v,p$1;const h=null!==(d=this.ut)&&void 0!==d?d:this.ut=[],m$1=[];let y,x,j=0,k=a$1.length-1,w=0,A=p$1.length-1;for(;j<=k&&w<=A;)if(null===a$1[j])j++;else if(null===a$1[k])k--;else if(h[j]===v[w])m$1[w]=f(a$1[j],p$1[w]),j++,w++;else if(h[k]===v[A])m$1[A]=f(a$1[k],p$1[A]),k--,A--;else if(h[j]===v[A])m$1[A]=f(a$1[j],p$1[A]),c$1(s,m$1[A+1],a$1[j]),j++,A--;else if(h[k]===v[w])m$1[w]=f(a$1[k],p$1[w]),c$1(s,a$1[j],a$1[k]),k--,w++;else if(void 0===y&&(y=u(v,w,A),x=u(h,j,k)),y.has(h[j]))if(y.has(h[k])){const e=x.get(v[w]),t=void 0!==e?a$1[e]:null;if(null===t){const e=c$1(s,a$1[j]);f(e,p$1[w]),m$1[w]=e;}else m$1[w]=f(t,p$1[w]),c$1(s,a$1[j],t),a$1[e]=null;w++;}else p(a$1[k]),k--;else p(a$1[j]),j++;for(;w<=A;){const e=c$1(s,m$1[A+1]);f(e,p$1[w]),m$1[w++]=e;}for(;j<=k;){const e=a$1[j++];null!==e&&p(e);}return this.ut=v,a(s,m$1),T}}); + const u$1=(e,s,t)=>{const r=new Map;for(let l=s;l<=t;l++)r.set(e[l],l);return r},c$3=e$1(class extends i$4{constructor(e){if(super(e),e.type!==t$3.CHILD)throw Error("repeat() can only be used in text expressions")}ct(e,s,t){let r;void 0===t?t=s:void 0!==s&&(r=s);const l=[],o=[];let i=0;for(const s of e)l[i]=r?r(s,i):i,o[i]=t(s,i),i++;return {values:o,keys:l}}render(e,s,t){return this.ct(e,s,t).values}update(s,[t,r,c]){var d;const a=m$2(s),{values:p$1,keys:v}=this.ct(t,r,c);if(!Array.isArray(a))return this.ut=v,p$1;const h=null!==(d=this.ut)&&void 0!==d?d:this.ut=[],m=[];let y,x,j=0,k=a.length-1,w=0,A=p$1.length-1;for(;j<=k&&w<=A;)if(null===a[j])j++;else if(null===a[k])k--;else if(h[j]===v[w])m[w]=f$2(a[j],p$1[w]),j++,w++;else if(h[k]===v[A])m[A]=f$2(a[k],p$1[A]),k--,A--;else if(h[j]===v[A])m[A]=f$2(a[j],p$1[A]),c$4(s,m[A+1],a[j]),j++,A--;else if(h[k]===v[w])m[w]=f$2(a[k],p$1[w]),c$4(s,a[j],a[k]),k--,w++;else if(void 0===y&&(y=u$1(v,w,A),x=u$1(h,j,k)),y.has(h[j]))if(y.has(h[k])){const e=x.get(v[w]),t=void 0!==e?a[e]:null;if(null===t){const e=c$4(s,a[j]);f$2(e,p$1[w]),m[w]=e;}else m[w]=f$2(t,p$1[w]),c$4(s,a[j],t),a[e]=null;w++;}else p(a[k]),k--;else p(a[j]),j++;for(;w<=A;){const e=c$4(s,m[A+1]);f$2(e,p$1[w]),m[w++]=e;}for(;j<=k;){const e=a[j++];null!==e&&p(e);}return this.ut=v,a$2(s,m),T}}); /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const o=e$1(class extends i{constructor(t$1){var i;if(super(t$1),t$1.type!==t.ATTRIBUTE||"class"!==t$1.name||(null===(i=t$1.strings)||void 0===i?void 0:i.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(t){return " "+Object.keys(t).filter((i=>t[i])).join(" ")+" "}update(i,[s]){var r,o;if(void 0===this.it){this.it=new Set,void 0!==i.strings&&(this.nt=new Set(i.strings.join(" ").split(/\s/).filter((t=>""!==t))));for(const t in s)s[t]&&!(null===(r=this.nt)||void 0===r?void 0:r.has(t))&&this.it.add(t);return this.render(s)}const e=i.element.classList;this.it.forEach((t=>{t in s||(e.remove(t),this.it.delete(t));}));for(const t in s){const i=!!s[t];i===this.it.has(t)||(null===(o=this.nt)||void 0===o?void 0:o.has(t))||(i?(e.add(t),this.it.add(t)):(e.remove(t),this.it.delete(t)));}return T}}); + */const o$1=e$1(class extends i$4{constructor(t){var i;if(super(t),t.type!==t$3.ATTRIBUTE||"class"!==t.name||(null===(i=t.strings)||void 0===i?void 0:i.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(t){return " "+Object.keys(t).filter((i=>t[i])).join(" ")+" "}update(i,[s]){var r,o;if(void 0===this.it){this.it=new Set,void 0!==i.strings&&(this.nt=new Set(i.strings.join(" ").split(/\s/).filter((t=>""!==t))));for(const t in s)s[t]&&!(null===(r=this.nt)||void 0===r?void 0:r.has(t))&&this.it.add(t);return this.render(s)}const e=i.element.classList;this.it.forEach((t=>{t in s||(e.remove(t),this.it.delete(t));}));for(const t in s){const i=!!s[t];i===this.it.has(t)||(null===(o=this.nt)||void 0===o?void 0:o.has(t))||(i?(e.add(t),this.it.add(t)):(e.remove(t),this.it.delete(t)));}return T}}); /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const l=l=>null!=l?l:A; + */const l$2=l=>null!=l?l:A$1; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */class e extends i{constructor(i){if(super(i),this.et=A,i.type!==t.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(r){if(r===A||null==r)return this.ft=void 0,this.et=r;if(r===T)return r;if("string"!=typeof r)throw Error(this.constructor.directiveName+"() called with a non-string value");if(r===this.et)return this.ft;this.et=r;const s=[r];return s.raw=s,this.ft={_$litType$:this.constructor.resultType,strings:s,values:[]}}}e.directiveName="unsafeHTML",e.resultType=1; + */class e extends i$4{constructor(i){if(super(i),this.et=A$1,i.type!==t$3.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(r){if(r===A$1||null==r)return this.ft=void 0,this.et=r;if(r===T)return r;if("string"!=typeof r)throw Error(this.constructor.directiveName+"() called with a non-string value");if(r===this.et)return this.ft;this.et=r;const s=[r];return s.raw=s,this.ft={_$litType$:this.constructor.resultType,strings:s,values:[]}}}e.directiveName="unsafeHTML",e.resultType=1; - const effectiveHtml = (strings, ...values) => { - const litStatic = getFeature("LitStatic"); - const fn = litStatic ? litStatic.html : x; - return fn(strings, ...values); - }; - const effectiveSvg = (strings, ...values) => { - const litStatic = getFeature("LitStatic"); - const fn = litStatic ? litStatic.svg : b; - return fn(strings, ...values); - }; - const litRender = (templateResult, container, options) => { - const openUI5Enablement = getFeature("OpenUI5Enablement"); - if (openUI5Enablement) { - templateResult = openUI5Enablement.wrapTemplateResultInBusyMarkup(effectiveHtml, options.host, templateResult); - } - D(templateResult, container, options); - }; - const scopeTag = (tag, tags, suffix) => { - const litStatic = getFeature("LitStatic"); - if (litStatic) { - return litStatic.unsafeStatic((tags || []).includes(tag) ? `${tag}-${suffix}` : tag); - } - }; + const m$1=(t,...n)=>{const e=m$9("LitStatic");return (e?e.html:x)(t,...n)},a$1=(t,...n)=>{const e=m$9("LitStatic");return (e?e.svg:b$1)(t,...n)},l$1=(t,n,e)=>{const r=m$9("OpenUI5Enablement");r&&(t=r.wrapTemplateResultInBusyMarkup(m$1,e.host,t)),D(t,n,e);},f$1=(t,n,e)=>{const r=m$9("LitStatic");if(r)return r.unsafeStatic((n||[]).includes(t)?`${t}-${e}`:t)}; - /** - * A decorator that converts a static class member into an accessor for the i18n bundle with a specified name - * - * @param { string } bundleName name of the i18n bundle to load - * @returns { i18nDecorator } - * - * ```ts - * class MyComponnet extends UI5Element { - * @i18n('@ui5/webcomponents') - * i18nBundle: I18nBundle; - * } - * ``` - */ - const i18n = (bundleName) => { - return (target, propertyName) => { - if (!target.metadata.i18n) { - target.metadata.i18n = {}; - } - target.metadata.i18n[propertyName] = { - bundleName, - target, - }; - }; - }; + const i$3=e=>(t,n)=>{t.metadata.i18n||(t.metadata.i18n={}),t.metadata.i18n[n]={bundleName:e,target:t};}; - /** - * Different types of ValueStates. - * - * @public - */ - var ValueState; - (function (ValueState) { - /** - * @public - */ - ValueState["None"] = "None"; - /** - * @public - */ - ValueState["Positive"] = "Positive"; - /** - * @public - */ - ValueState["Critical"] = "Critical"; - /** - * @public - */ - ValueState["Negative"] = "Negative"; - /** - * @public - */ - ValueState["Information"] = "Information"; - })(ValueState || (ValueState = {})); - var ValueState$1 = ValueState; + var o=(i=>(i.None="None",i.Positive="Positive",i.Critical="Critical",i.Negative="Negative",i.Information="Information",i))(o||{}); - const getEffectiveAriaLabelText = (el) => { - const accessibleEl = el; - if (!accessibleEl.accessibleNameRef) { - if (accessibleEl.accessibleName) { - return accessibleEl.accessibleName; - } - return undefined; - } - return getAllAccessibleNameRefTexts(el); - }; - /** - * - * @param {HTMLElement} el Defines the HTMLElement, for which you need to get all related texts - */ - const getAllAccessibleNameRefTexts = (el) => { - const ids = el.accessibleNameRef?.split(" ") ?? []; - let result = ""; - ids.forEach((elementId, index) => { - const element = _getReferencedElementById(el, elementId); - const text = `${element && element.textContent ? element.textContent : ""}`; - if (text) { - result += text; - if (index < ids.length - 1) { - result += " "; - } - } - }); - return result; - }; - const _getReferencedElementById = (el, elementId) => { - return el.getRootNode().querySelector(`[id='${elementId}']`) || document.getElementById(elementId); - }; + const A=e=>{const t=e;return t.accessibleNameRef?E(e):t.accessibleName?t.accessibleName:void 0},E=e=>{const t=e.accessibleNameRef?.split(" ")??[];let s="";return t.forEach((n,c)=>{const l=m(e,n),a=`${l&&l.textContent?l.textContent:""}`;a&&(s+=a,ce.getRootNode().querySelector(`[id='${t}']`)||document.getElementById(t); - const KeyCodes = { - BACKSPACE: 8, - TAB: 9, - ENTER: 13, - SHIFT: 16, - CONTROL: 17, - ALT: 18, - BREAK: 19, - CAPS_LOCK: 20, - ESCAPE: 27, - SPACE: 32, - PAGE_UP: 33, - PAGE_DOWN: 34, - END: 35, - HOME: 36, - ARROW_LEFT: 37, - ARROW_UP: 38, - ARROW_RIGHT: 39, - ARROW_DOWN: 40, - PRINT: 44, - INSERT: 45, - DELETE: 46, - DIGIT_0: 48, - DIGIT_1: 49, - DIGIT_2: 50, - DIGIT_3: 51, - DIGIT_4: 52, - DIGIT_5: 53, - DIGIT_6: 54, - DIGIT_7: 55, - DIGIT_8: 56, - DIGIT_9: 57, - A: 65, - B: 66, - C: 67, - D: 68, - E: 69, - F: 70, - G: 71, - H: 72, - I: 73, - J: 74, - K: 75, - L: 76, - M: 77, - N: 78, - O: 79, - P: 80, - Q: 81, - R: 82, - S: 83, - T: 84, - U: 85, - V: 86, - W: 87, - X: 88, - Y: 89, - Z: 90, - WINDOWS: 91, - CONTEXT_MENU: 93, - TURN_OFF: 94, - SLEEP: 95, - NUMPAD_0: 96, - NUMPAD_1: 97, - NUMPAD_2: 98, - NUMPAD_3: 99, - NUMPAD_4: 100, - NUMPAD_5: 101, - NUMPAD_6: 102, - NUMPAD_7: 103, - NUMPAD_8: 104, - NUMPAD_9: 105, - NUMPAD_ASTERISK: 106, - NUMPAD_PLUS: 107, - NUMPAD_MINUS: 109, - NUMPAD_COMMA: 110, - NUMPAD_SLASH: 111, - F1: 112, - F2: 113, - F3: 114, - F4: 115, - F5: 116, - F6: 117, - F7: 118, - F8: 119, - F9: 120, - F10: 121, - F11: 122, - F12: 123, - NUM_LOCK: 144, - SCROLL_LOCK: 145, - COLON: 186, - PLUS: 187, - COMMA: 188, - SLASH: 189, - DOT: 190, - PIPE: 191, - SEMICOLON: 192, - MINUS: 219, - GREAT_ACCENT: 220, - EQUALS: 221, - SINGLE_QUOTE: 222, - BACKSLASH: 226, - }; - const isEnter = (event) => (event.key ? event.key === "Enter" : event.keyCode === KeyCodes.ENTER) && !hasModifierKeys(event); - const isSpace = (event) => (event.key ? (event.key === "Spacebar" || event.key === " ") : event.keyCode === KeyCodes.SPACE) && !hasModifierKeys(event); - const hasModifierKeys = (event) => event.shiftKey || event.altKey || getCtrlKey(event); - const getCtrlKey = (event) => !!(event.metaKey || event.ctrlKey); // double negation doesn't have effect on boolean but ensures null and undefined are equivalent to false. + const y={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CONTROL:17,ALT:18,BREAK:19,CAPS_LOCK:20,ESCAPE:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,ARROW_LEFT:37,ARROW_UP:38,ARROW_RIGHT:39,ARROW_DOWN:40,PRINT:44,INSERT:45,DELETE:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_4:52,DIGIT_5:53,DIGIT_6:54,DIGIT_7:55,DIGIT_8:56,DIGIT_9:57,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,WINDOWS:91,CONTEXT_MENU:93,TURN_OFF:94,SLEEP:95,NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_ASTERISK:106,NUMPAD_PLUS:107,NUMPAD_MINUS:109,NUMPAD_COMMA:110,NUMPAD_SLASH:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUM_LOCK:144,SCROLL_LOCK:145,COLON:186,PLUS:187,COMMA:188,SLASH:189,DOT:190,PIPE:191,SEMICOLON:192,MINUS:219,GREAT_ACCENT:220,EQUALS:221,SINGLE_QUOTE:222,BACKSLASH:226},b=o=>(o.key?o.key==="Enter":o.keyCode===y.ENTER)&&!a(o),i$2=o=>(o.key?o.key==="Spacebar"||o.key===" ":o.keyCode===y.SPACE)&&!a(o),a=o=>o.shiftKey||o.altKey||k(o),k=o=>!!(o.metaKey||o.ctrlKey); - /** - * Supported icon collection aliases. - * - * Users might specify a collection, using both the key and the value in the following key-value pairs, - * e.g the following pairs are completely exchangeable: - * - * - "SAP-icons/accept" and "SAP-icons-v4/accept" - * - "horizon/accept" and "SAP-icons-v5/accept" - * - "SAP-icons-TNT/actor" and "tnt/actor" - * - "BusinessSuiteInAppSymbols/3d" and "business-suite/3d" - */ - var IconCollectionsAlias; - (function (IconCollectionsAlias) { - IconCollectionsAlias["SAP-icons"] = "SAP-icons-v4"; - IconCollectionsAlias["horizon"] = "SAP-icons-v5"; - IconCollectionsAlias["SAP-icons-TNT"] = "tnt"; - IconCollectionsAlias["BusinessSuiteInAppSymbols"] = "business-suite"; - })(IconCollectionsAlias || (IconCollectionsAlias = {})); - /** - * Returns the collection name for a given alias: - * - * - "SAP-icons-TNT"resolves to "tnt" - * - "BusinessSuiteInAppSymbols" resolves to "business-suite" - * - "horizon" resolves to "SAP-icons-v5" - * - * @param { string } collectionName - * @return { string } the normalized collection name - */ - const getIconCollectionByAlias = (collectionName) => { - if (IconCollectionsAlias[collectionName]) { - return IconCollectionsAlias[collectionName]; - } - return collectionName; - }; + var t$2=(s=>(s["SAP-icons"]="SAP-icons-v4",s.horizon="SAP-icons-v5",s["SAP-icons-TNT"]="tnt",s.BusinessSuiteInAppSymbols="business-suite",s))(t$2||{});const n$1=e=>t$2[e]?t$2[e]:e; - var RegisteredIconCollection; - (function (RegisteredIconCollection) { - RegisteredIconCollection["SAPIconsV4"] = "SAP-icons-v4"; - RegisteredIconCollection["SAPIconsV5"] = "SAP-icons-v5"; - RegisteredIconCollection["SAPIconsTNTV2"] = "tnt-v2"; - RegisteredIconCollection["SAPIconsTNTV3"] = "tnt-v3"; - RegisteredIconCollection["SAPBSIconsV1"] = "business-suite-v1"; - RegisteredIconCollection["SAPBSIconsV2"] = "business-suite-v2"; - })(RegisteredIconCollection || (RegisteredIconCollection = {})); - const iconCollections = new Map(); - iconCollections.set("SAP-icons", { - "legacy": RegisteredIconCollection.SAPIconsV4, - "sap_horizon": RegisteredIconCollection.SAPIconsV5, - }); - iconCollections.set("tnt", { - "legacy": RegisteredIconCollection.SAPIconsTNTV2, - "sap_horizon": RegisteredIconCollection.SAPIconsTNTV3, - }); - iconCollections.set("business-suite", { - "legacy": RegisteredIconCollection.SAPBSIconsV1, - "sap_horizon": RegisteredIconCollection.SAPBSIconsV2, - }); - /** - * Registers collection version per theme. - * **For exmaple:** registerIconCollectionForTheme("my-custom-icons", {"sap_horizon": "my-custom-icons-v5"}) - * @param { string } collectionName - * @param { ThemeToCollectionMap } themeCollectionMap - */ - const registerIconCollectionForTheme = (collectionName, themeCollectionMap) => { - if (iconCollections.has(collectionName)) { - iconCollections.set(collectionName, { ...themeCollectionMap, ...iconCollections.get(collectionName) }); - return; - } - iconCollections.set(collectionName, themeCollectionMap); - }; - const getIconCollectionForTheme = (collectionName) => { - const themeFamily = isLegacyThemeFamily() ? "legacy" : "sap_horizon"; - return iconCollections.has(collectionName) ? iconCollections.get(collectionName)[themeFamily] : collectionName; - }; + var t$1=(o=>(o.SAPIconsV4="SAP-icons-v4",o.SAPIconsV5="SAP-icons-v5",o.SAPIconsTNTV2="tnt-v2",o.SAPIconsTNTV3="tnt-v3",o.SAPBSIconsV1="business-suite-v1",o.SAPBSIconsV2="business-suite-v2",o))(t$1||{});const s$1=new Map;s$1.set("SAP-icons",{legacy:"SAP-icons-v4",sap_horizon:"SAP-icons-v5"}),s$1.set("tnt",{legacy:"tnt-v2",sap_horizon:"tnt-v3"}),s$1.set("business-suite",{legacy:"business-suite-v1",sap_horizon:"business-suite-v2"});const c$2=(n,e)=>{if(s$1.has(n)){s$1.set(n,{...e,...s$1.get(n)});return}s$1.set(n,e);},r=n=>{const e=i$a()?"legacy":"sap_horizon";return s$1.has(n)?s$1.get(n)[e]:n}; - const IconCollectionConfiguration = new Map(); - /** - * Returns the configured default icon collection for a given theme. - * - * @param { string } theme - * @public - * @returns { string | undefined } - */ - const getDefaultIconCollection = (theme) => { - return IconCollectionConfiguration.get(theme); - }; + const t=new Map,c$1=n=>t.get(n); - /** - * Returns the effective theme dependant icon collection: - * - * - "no collection" resolves to "SAP-icons-v4" in "Quartz" and to "SAP-icons-v5" in "Horizon" - * - "tnt" (and its alias "SAP-icons-TNT") resolves to "tnt-v2" in "Quartz" and resolves to "tnt-v3" in "Horizon" - * - "business-suite" (and its alias "BusinessSuiteInAppSymbols") resolves to "business-suite-v1" in "Quartz" and resolves to "business-suite-v2" in "Horizon" - * - * @param { IconCollection } collectionName - * @returns { IconCollection } the effective collection name - */ - const getEffectiveIconCollection = (collectionName) => { - const defaultIconCollection = getDefaultIconCollection(getTheme()); - // no collection + default collection, configured via setDefaultIconCollection - return the configured icon collection. - if (!collectionName && defaultIconCollection) { - return getIconCollectionByAlias(defaultIconCollection); - } - // no collection - return "SAP-icons-v4" or "SAP-icons-v5". - if (!collectionName) { - return getIconCollectionForTheme("SAP-icons"); - } - // has collection - return "SAP-icons-v4", "SAP-icons-v5", "tnt-v1", "tnt-v2", "business-suite-v1", "business-suite-v2", or custom ones. - return getIconCollectionForTheme(collectionName); - }; + const i$1=o=>{const t=c$1(r$b());return !o&&t?n$1(t):o?r(o):r("SAP-icons")}; - const DEFAULT_THEME_FAMILY = "legacy"; // includes sap_fiori_* - const loaders = new Map(); - const registry = getSharedResource("SVGIcons.registry", new Map()); - const iconCollectionPromises = getSharedResource("SVGIcons.promises", new Map()); - const ICON_NOT_FOUND$1 = "ICON_NOT_FOUND"; - const _loadIconCollectionOnce = async (collectionName) => { - if (!iconCollectionPromises.has(collectionName)) { - if (!loaders.has(collectionName)) { - throw new Error(`No loader registered for the ${collectionName} icons collection. Probably you forgot to import the "AllIcons.js" module for the respective package.`); - } - const loadIcons = loaders.get(collectionName); - iconCollectionPromises.set(collectionName, loadIcons(collectionName)); - } - return iconCollectionPromises.get(collectionName); - }; - const _fillRegistry = (bundleData) => { - Object.keys(bundleData.data).forEach(iconName => { - const iconData = bundleData.data[iconName]; - registerIcon(iconName, { - pathData: (iconData.path || iconData.paths), - ltr: iconData.ltr, - accData: iconData.acc, - collection: bundleData.collection, - packageName: bundleData.packageName, - }); - }); - }; - // set - const registerIcon = (name, iconData) => { - const key = `${iconData.collection}/${name}`; - registry.set(key, { - pathData: iconData.pathData, - ltr: iconData.ltr, - accData: iconData.accData, - packageName: iconData.packageName, - customTemplate: iconData.customTemplate, - viewBox: iconData.viewBox, - collection: iconData.collection, - }); - }; - /** - * Processes the full icon name and splits it into - "name", "collection". - * - removes legacy protocol ("sap-icon://") - * - resolves aliases (f.e "SAP-icons-TNT/actor" => "tnt/actor") - * - * @param { string } name - * @return { object } - */ - const processName = (name) => { - // silently support ui5-compatible URIs - if (name.startsWith("sap-icon://")) { - name = name.replace("sap-icon://", ""); - } - let collection; - [name, collection] = name.split("/").reverse(); - name = name.replace("icon-", ""); - if (collection) { - collection = getIconCollectionByAlias(collection); - } - return { name, collection }; - }; - const getIconDataSync = (iconName) => { - const { name, collection } = processName(iconName); - return getRegisteredIconData(collection, name); - }; - const getIconData = async (iconName) => { - const { name, collection } = processName(iconName); - let iconData = ICON_NOT_FOUND$1; - try { - iconData = (await _loadIconCollectionOnce(getEffectiveIconCollection(collection))); - } - catch (error) { - const e = error; - console.error(e.message); /* eslint-disable-line */ - } - if (iconData === ICON_NOT_FOUND$1) { - return iconData; - } - const registeredIconData = getRegisteredIconData(collection, name); - if (registeredIconData) { - return registeredIconData; - } - // not filled by another await. many getters will await on the same loader, but fill only once - if (Array.isArray(iconData)) { - iconData.forEach(data => { - _fillRegistry(data); - registerIconCollectionForTheme(collection, { [data.themeFamily || DEFAULT_THEME_FAMILY]: data.collection }); - }); - } - else { - _fillRegistry(iconData); - } - return getRegisteredIconData(collection, name); - }; - const getRegisteredIconData = (collection, name) => { - const registryKey = `${getEffectiveIconCollection(collection)}/${name}`; - return registry.get(registryKey); - }; + const w="legacy",c=new Map,s=m$d("SVGIcons.registry",new Map),i=m$d("SVGIcons.promises",new Map),l="ICON_NOT_FOUND",N=async e=>{if(!i.has(e)){if(!c.has(e))throw new Error(`No loader registered for the ${e} icons collection. Probably you forgot to import the "AllIcons.js" module for the respective package.`);const t=c.get(e);i.set(e,t(e));}return i.get(e)},I=e=>{Object.keys(e.data).forEach(t=>{const o=e.data[t];f(t,{pathData:o.path||o.paths,ltr:o.ltr,accData:o.acc,collection:e.collection,packageName:e.packageName});});},f=(e,t)=>{const o=`${t.collection}/${e}`;s.set(o,{pathData:t.pathData,ltr:t.ltr,accData:t.accData,packageName:t.packageName,customTemplate:t.customTemplate,viewBox:t.viewBox,collection:t.collection});},d=e=>{e.startsWith("sap-icon://")&&(e=e.replace("sap-icon://",""));let t;return [e,t]=e.split("/").reverse(),e=e.replace("icon-",""),t&&(t=n$1(t)),{name:e,collection:t}},u=e=>{const{name:t,collection:o}=d(e);return g(o,t)},n=async e=>{const{name:t,collection:o}=d(e);let r=l;try{r=await N(i$1(o));}catch(a){console.error(a.message);}if(r===l)return r;const p=g(o,t);return p||(Array.isArray(r)?r.forEach(a=>{I(a),c$2(o,{[a.themeFamily||w]:a.collection});}):I(r),g(o,t))},g=(e,t)=>{const o=`${i$1(e)}/${t}`;return s.get(o)}; const name$7 = "accept"; const pathData$7 = "M456 94q5 5 5 11 0 4-2 8L237 439q-4 8-8.5 8.5t-5.5.5q-7 0-12-5L60 276q-5-5-5-10l.5-3.5L61 254l25-25q6-6 12-6t11 6l96 96q5 5 12 5l4.5-.5 8.5-8.5L405 72q4-7 8.5-7.5t5.5-.5q6 0 11 4z"; @@ -3928,7 +242,7 @@ sap.ui.define((function () { 'use strict'; const collection$7 = "SAP-icons-v4"; const packageName$7 = "@ui5/webcomponents-icons"; - registerIcon(name$7, { pathData: pathData$7, ltr: ltr$7, collection: collection$7, packageName: packageName$7 }); + f(name$7, { pathData: pathData$7, ltr: ltr$7, collection: collection$7, packageName: packageName$7 }); const name$6 = "accept"; const pathData$6 = "M187 416q-12 0-20-9L71 299q-7-7-7-17 0-11 7.5-18.5T90 256q12 0 19 9l77 87 217-247q8-9 19-9t18.5 7.5T448 122q0 10-6 16L206 407q-7 9-19 9z"; @@ -3936,7 +250,7 @@ sap.ui.define((function () { 'use strict'; const collection$6 = "SAP-icons-v5"; const packageName$6 = "@ui5/webcomponents-icons"; - registerIcon(name$6, { pathData: pathData$6, ltr: ltr$6, collection: collection$6, packageName: packageName$6 }); + f(name$6, { pathData: pathData$6, ltr: ltr$6, collection: collection$6, packageName: packageName$6 }); const name$5 = "complete"; const pathData$5 = "M492 25q4 4 4 9 0 3-2 7L309 313q-3 6-7 6.5t-5 .5q-6 0-10-4L162 177q-4-5-4-9 0-5 4-9l21-21q5-5 10-5t9 5l80 80q4 4 9 4 1 0 5-.5t7-7.5L449 7q3-6 7-6.5t5-.5q5 0 9 4zm-60 295h32v128q0 14-9.5 23t-22.5 9H48q-14 0-23-9t-9-23V64q0-13 9-22.5T48 32h128v32H48v384h384V320z"; @@ -3944,7 +258,7 @@ sap.ui.define((function () { 'use strict'; const collection$5 = "SAP-icons-v4"; const packageName$5 = "@ui5/webcomponents-icons"; - registerIcon(name$5, { pathData: pathData$5, ltr: ltr$5, collection: collection$5, packageName: packageName$5 }); + f(name$5, { pathData: pathData$5, ltr: ltr$5, collection: collection$5, packageName: packageName$5 }); const name$4 = "complete"; const pathData$4 = "M438 224q11 0 18.5 7.5T464 250v140q0 38-26 64t-64 26H106q-38 0-64-26t-26-64V122q0-38 26-64t64-26h237q11 0 18 7.5t7 18.5-7 18-18 7H106q-16 0-27.5 11.5T67 122v268q0 16 11.5 27.5T106 429h268q16 0 27.5-11.5T413 390V250q0-11 7-18.5t18-7.5zm32-192q11 0 18.5 7.5T496 58t-7 17L257 312q-6 8-18 8-10 0-18-8l-70-71q-7-7-7-18t7.5-18 18.5-7 18 7l51 53L452 40q8-8 18-8z"; @@ -3952,7 +266,7 @@ sap.ui.define((function () { 'use strict'; const collection$4 = "SAP-icons-v5"; const packageName$4 = "@ui5/webcomponents-icons"; - registerIcon(name$4, { pathData: pathData$4, ltr: ltr$4, collection: collection$4, packageName: packageName$4 }); + f(name$4, { pathData: pathData$4, ltr: ltr$4, collection: collection$4, packageName: packageName$4 }); const name$3 = "border"; const pathData$3 = "M448 32q13 0 22.5 9t9.5 23v384q0 14-9.5 23t-22.5 9H64q-14 0-23-9t-9-23V64q0-14 9-23t23-9h384zm0 32H64v384h384V64z"; @@ -3960,7 +274,7 @@ sap.ui.define((function () { 'use strict'; const collection$3 = "SAP-icons-v4"; const packageName$3 = "@ui5/webcomponents-icons"; - registerIcon(name$3, { pathData: pathData$3, ltr: ltr$3, collection: collection$3, packageName: packageName$3 }); + f(name$3, { pathData: pathData$3, ltr: ltr$3, collection: collection$3, packageName: packageName$3 }); const name$2 = "border"; const pathData$2 = "M390 480H122q-38 0-64-26t-26-64V122q0-38 26-64t64-26h268q38 0 64 26t26 64v268q0 38-26 64t-64 26zM122 83q-17 0-28 11t-11 28v268q0 17 11 28t28 11h268q17 0 28-11t11-28V122q0-17-11-28t-28-11H122z"; @@ -3968,7 +282,7 @@ sap.ui.define((function () { 'use strict'; const collection$2 = "SAP-icons-v5"; const packageName$2 = "@ui5/webcomponents-icons"; - registerIcon(name$2, { pathData: pathData$2, ltr: ltr$2, collection: collection$2, packageName: packageName$2 }); + f(name$2, { pathData: pathData$2, ltr: ltr$2, collection: collection$2, packageName: packageName$2 }); const name$1 = "tri-state"; const pathData$1 = "M448 32q13 0 22.5 9.5T480 64v384q0 14-9.5 23t-22.5 9H64q-14 0-23-9t-9-23V64q0-13 9-22.5T64 32h384zm0 32H64v384h384V64zM160 345V169q0-8 8-8h176q8 0 8 8v176q0 8-8 8H168q-8 0-8-8z"; @@ -3976,7 +290,7 @@ sap.ui.define((function () { 'use strict'; const collection$1 = "SAP-icons-v4"; const packageName$1 = "@ui5/webcomponents-icons"; - registerIcon(name$1, { pathData: pathData$1, ltr: ltr$1, collection: collection$1, packageName: packageName$1 }); + f(name$1, { pathData: pathData$1, ltr: ltr$1, collection: collection$1, packageName: packageName$1 }); const name = "tri-state"; const pathData = "M390 32q38 0 64 26t26 64v268q0 38-26 64t-64 26H122q-38 0-64-26t-26-64V122q0-38 26-64t64-26h268zm39 90q0-17-11-28t-28-11H122q-17 0-28 11t-11 28v268q0 17 11 28t28 11h268q17 0 28-11t11-28V122zm-77 38v192H160V160h192z"; @@ -3984,15 +298,15 @@ sap.ui.define((function () { 'use strict'; const collection = "SAP-icons-v5"; const packageName = "@ui5/webcomponents-icons"; - registerIcon(name, { pathData, ltr, collection, packageName }); + f(name, { pathData, ltr, collection, packageName }); /* eslint no-unused-vars: 0 */ - function block0$2(context, tags, suffix) { return effectiveHtml `${blockSVG1.call(this, context, tags, suffix)}`; } - function block1$1(context, tags, suffix) { return effectiveSvg `${l(this.effectiveAccessibleName)}`; } - function block2$1(context, tags, suffix) { return effectiveSvg `${l(this.customSvg)}`; } - function block3$1(context, tags, suffix, item, index) { return effectiveSvg ``; } + function block0$2(context, tags, suffix) { return m$1 `${blockSVG1.call(this, context, tags, suffix)}`; } + function block1$1(context, tags, suffix) { return a$1 `${l$2(this.effectiveAccessibleName)}`; } + function block2$1(context, tags, suffix) { return a$1 `${l$2(this.customSvg)}`; } + function block3$1(context, tags, suffix, item, index) { return a$1 ``; } function blockSVG1(context, tags, suffix) { - return effectiveSvg `${this.hasIconTooltip ? block1$1.call(this, context, tags, suffix) : undefined}${this.customSvg ? block2$1.call(this, context, tags, suffix) : undefined}${c(this.pathData, (item, index) => item._id || index, (item, index) => block3$1.call(this, context, tags, suffix, item, index))}`; + return a$1 `${this.hasIconTooltip ? block1$1.call(this, context, tags, suffix) : undefined}${this.customSvg ? block2$1.call(this, context, tags, suffix) : undefined}${c$3(this.pathData, (item, index) => item._id || index, (item, index) => block3$1.call(this, context, tags, suffix, item, index))}`; } /** @@ -4031,8 +345,8 @@ sap.ui.define((function () { 'use strict'; const styleData$3 = { packageName: "@ui5/webcomponents", fileName: "themes/sap_horizon/parameters-bundle.css.ts", content: `:root{--ui5-v2-5-0-avatar-hover-box-shadow-offset: 0px 0px 0px .0625rem;--ui5-v2-5-0-avatar-initials-color: var(--sapContent_ImagePlaceholderForegroundColor);--ui5-v2-5-0-avatar-border-radius-img-deduction: .0625rem;--_ui5-v2-5-0_avatar_outline: var(--sapContent_FocusWidth) var(--sapContent_FocusStyle) var(--sapContent_FocusColor);--_ui5-v2-5-0_avatar_focus_width: .0625rem;--_ui5-v2-5-0_avatar_focus_color: var(--sapContent_FocusColor);--_ui5-v2-5-0_avatar_overflow_button_focus_offset: .0625rem;--_ui5-v2-5-0_avatar_focus_offset: .1875rem;--ui5-v2-5-0-avatar-initials-border: .0625rem solid var(--sapAvatar_1_BorderColor);--ui5-v2-5-0-avatar-border-radius: var(--sapElement_BorderCornerRadius);--_ui5-v2-5-0_avatar_fontsize_XS: 1rem;--_ui5-v2-5-0_avatar_fontsize_S: 1.125rem;--_ui5-v2-5-0_avatar_fontsize_M: 1.5rem;--_ui5-v2-5-0_avatar_fontsize_L: 2.25rem;--_ui5-v2-5-0_avatar_fontsize_XL: 3rem;--ui5-v2-5-0-avatar-accent1: var(--sapAvatar_1_Background);--ui5-v2-5-0-avatar-accent2: var(--sapAvatar_2_Background);--ui5-v2-5-0-avatar-accent3: var(--sapAvatar_3_Background);--ui5-v2-5-0-avatar-accent4: var(--sapAvatar_4_Background);--ui5-v2-5-0-avatar-accent5: var(--sapAvatar_5_Background);--ui5-v2-5-0-avatar-accent6: var(--sapAvatar_6_Background);--ui5-v2-5-0-avatar-accent7: var(--sapAvatar_7_Background);--ui5-v2-5-0-avatar-accent8: var(--sapAvatar_8_Background);--ui5-v2-5-0-avatar-accent9: var(--sapAvatar_9_Background);--ui5-v2-5-0-avatar-accent10: var(--sapAvatar_10_Background);--ui5-v2-5-0-avatar-placeholder: var(--sapContent_ImagePlaceholderBackground);--ui5-v2-5-0-avatar-accent1-color: var(--sapAvatar_1_TextColor);--ui5-v2-5-0-avatar-accent2-color: var(--sapAvatar_2_TextColor);--ui5-v2-5-0-avatar-accent3-color: var(--sapAvatar_3_TextColor);--ui5-v2-5-0-avatar-accent4-color: var(--sapAvatar_4_TextColor);--ui5-v2-5-0-avatar-accent5-color: var(--sapAvatar_5_TextColor);--ui5-v2-5-0-avatar-accent6-color: var(--sapAvatar_6_TextColor);--ui5-v2-5-0-avatar-accent7-color: var(--sapAvatar_7_TextColor);--ui5-v2-5-0-avatar-accent8-color: var(--sapAvatar_8_TextColor);--ui5-v2-5-0-avatar-accent9-color: var(--sapAvatar_9_TextColor);--ui5-v2-5-0-avatar-accent10-color: var(--sapAvatar_10_TextColor);--ui5-v2-5-0-avatar-placeholder-color: var(--sapContent_ImagePlaceholderForegroundColor);--ui5-v2-5-0-avatar-accent1-border-color: var(--sapAvatar_1_BorderColor);--ui5-v2-5-0-avatar-accent2-border-color: var(--sapAvatar_2_BorderColor);--ui5-v2-5-0-avatar-accent3-border-color: var(--sapAvatar_3_BorderColor);--ui5-v2-5-0-avatar-accent4-border-color: var(--sapAvatar_4_BorderColor);--ui5-v2-5-0-avatar-accent5-border-color: var(--sapAvatar_5_BorderColor);--ui5-v2-5-0-avatar-accent6-border-color: var(--sapAvatar_6_BorderColor);--ui5-v2-5-0-avatar-accent7-border-color: var(--sapAvatar_7_BorderColor);--ui5-v2-5-0-avatar-accent8-border-color: var(--sapAvatar_8_BorderColor);--ui5-v2-5-0-avatar-accent9-border-color: var(--sapAvatar_9_BorderColor);--ui5-v2-5-0-avatar-accent10-border-color: var(--sapAvatar_10_BorderColor);--ui5-v2-5-0-avatar-placeholder-border-color: var(--sapContent_ImagePlaceholderBackground);--_ui5-v2-5-0_avatar_icon_XS: var(--_ui5-v2-5-0_avatar_fontsize_XS);--_ui5-v2-5-0_avatar_icon_S: var(--_ui5-v2-5-0_avatar_fontsize_S);--_ui5-v2-5-0_avatar_icon_M: var(--_ui5-v2-5-0_avatar_fontsize_M);--_ui5-v2-5-0_avatar_icon_L: var(--_ui5-v2-5-0_avatar_fontsize_L);--_ui5-v2-5-0_avatar_icon_XL: var(--_ui5-v2-5-0_avatar_fontsize_XL);--_ui5-v2-5-0_avatar_group_button_focus_border: none;--_ui5-v2-5-0_avatar_group_focus_border_radius: .375rem;--_ui5-v2-5-0-tag-height: 1rem;--_ui5-v2-5-0-tag-icon-width: .75rem;--ui5-v2-5-0-tag-text-shadow: var(--sapContent_TextShadow);--ui5-v2-5-0-tag-contrast-text-shadow: var(--sapContent_ContrastTextShadow);--ui5-v2-5-0-tag-information-text-shadow: var(--ui5-v2-5-0-tag-text-shadow);--ui5-v2-5-0-tag-set2-color-scheme-1-color: var(--sapIndicationColor_1);--ui5-v2-5-0-tag-set2-color-scheme-1-background: var(--sapIndicationColor_1b);--ui5-v2-5-0-tag-set2-color-scheme-1-border: var(--sapIndicationColor_1b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-1-hover-background: var(--sapIndicationColor_1b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-1-active-color: var(--sapIndicationColor_1_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-1-active-background: var(--sapIndicationColor_1_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-1-active-border: var(--sapIndicationColor_1_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-2-color: var(--sapIndicationColor_2);--ui5-v2-5-0-tag-set2-color-scheme-2-background: var(--sapIndicationColor_2b);--ui5-v2-5-0-tag-set2-color-scheme-2-border: var(--sapIndicationColor_2b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-2-hover-background: var(--sapIndicationColor_2b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-2-active-color: var(--sapIndicationColor_2_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-2-active-background: var(--sapIndicationColor_2_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-2-active-border: var(--sapIndicationColor_2_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-3-color: var(--sapIndicationColor_3);--ui5-v2-5-0-tag-set2-color-scheme-3-background: var(--sapIndicationColor_3b);--ui5-v2-5-0-tag-set2-color-scheme-3-border: var(--sapIndicationColor_3b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-3-hover-background: var(--sapIndicationColor_3b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-3-active-color: var(--sapIndicationColor_3_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-3-active-background: var(--sapIndicationColor_3_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-3-active-border: var(--sapIndicationColor_3_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-4-color: var(--sapIndicationColor_4);--ui5-v2-5-0-tag-set2-color-scheme-4-background: var(--sapIndicationColor_4b);--ui5-v2-5-0-tag-set2-color-scheme-4-border: var(--sapIndicationColor_4b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-4-hover-background: var(--sapIndicationColor_4b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-4-active-color: var(--sapIndicationColor_4_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-4-active-background: var(--sapIndicationColor_4_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-4-active-border: var(--sapIndicationColor_4_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-5-color: var(--sapIndicationColor_5);--ui5-v2-5-0-tag-set2-color-scheme-5-background: var(--sapIndicationColor_5b);--ui5-v2-5-0-tag-set2-color-scheme-5-border: var(--sapIndicationColor_5b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-5-hover-background: var(--sapIndicationColor_5b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-5-active-color: var(--sapIndicationColor_5_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-5-active-background: var(--sapIndicationColor_5_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-5-active-border: var(--sapIndicationColor_5_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-6-color: var(--sapIndicationColor_6);--ui5-v2-5-0-tag-set2-color-scheme-6-background: var(--sapIndicationColor_6b);--ui5-v2-5-0-tag-set2-color-scheme-6-border: var(--sapIndicationColor_6b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-6-hover-background: var(--sapIndicationColor_6b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-6-active-color: var(--sapIndicationColor_6_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-6-active-background: var(--sapIndicationColor_6_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-6-active-border: var(--sapIndicationColor_6_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-7-color: var(--sapIndicationColor_7);--ui5-v2-5-0-tag-set2-color-scheme-7-background: var(--sapIndicationColor_7b);--ui5-v2-5-0-tag-set2-color-scheme-7-border: var(--sapIndicationColor_7b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-7-hover-background: var(--sapIndicationColor_7b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-7-active-color: var(--sapIndicationColor_7_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-7-active-background: var(--sapIndicationColor_7_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-7-active-border: var(--sapIndicationColor_7_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-8-color: var(--sapIndicationColor_8);--ui5-v2-5-0-tag-set2-color-scheme-8-background: var(--sapIndicationColor_8b);--ui5-v2-5-0-tag-set2-color-scheme-8-border: var(--sapIndicationColor_8b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-8-hover-background: var(--sapIndicationColor_8b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-8-active-color: var(--sapIndicationColor_8_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-8-active-background: var(--sapIndicationColor_8_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-8-active-border: var(--sapIndicationColor_8_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-9-color: var(--sapIndicationColor_9);--ui5-v2-5-0-tag-set2-color-scheme-9-background: var(--sapIndicationColor_9b);--ui5-v2-5-0-tag-set2-color-scheme-9-border: var(--sapIndicationColor_9b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-9-hover-background: var(--sapIndicationColor_9b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-9-active-color: var(--sapIndicationColor_9_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-9-active-background: var(--sapIndicationColor_9_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-9-active-border: var(--sapIndicationColor_9_Active_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-10-color: var(--sapIndicationColor_10);--ui5-v2-5-0-tag-set2-color-scheme-10-background: var(--sapIndicationColor_10b);--ui5-v2-5-0-tag-set2-color-scheme-10-border: var(--sapIndicationColor_10b_BorderColor);--ui5-v2-5-0-tag-set2-color-scheme-10-hover-background: var(--sapIndicationColor_10b_Hover_Background);--ui5-v2-5-0-tag-set2-color-scheme-10-active-color: var(--sapIndicationColor_10_Active_TextColor);--ui5-v2-5-0-tag-set2-color-scheme-10-active-background: var(--sapIndicationColor_10_Active_Background);--ui5-v2-5-0-tag-set2-color-scheme-10-active-border: var(--sapIndicationColor_10_Active_BorderColor);--_ui5-v2-5-0-tag-height_size_l: 1.5rem;--_ui5-v2-5-0-tag-min-width_size_l: 1.75rem;--_ui5-v2-5-0-tag-font-size_size_l: 1.25rem;--_ui5-v2-5-0-tag-icon_min_width_size_l: 1.25rem;--_ui5-v2-5-0-tag-icon_min_height_size_l:1.25rem;--_ui5-v2-5-0-tag-icon_height_size_l: 1.25rem;--_ui5-v2-5-0-tag-text_padding_size_l: .125rem .25rem;--_ui5-v2-5-0-tag-text-height_size_l: 1.5rem;--_ui5-v2-5-0-tag-text-padding: .1875rem .25rem;--_ui5-v2-5-0-tag-padding-inline-icon-only: .313rem;--_ui5-v2-5-0-tag-text-transform: none;--_ui5-v2-5-0-tag-icon-gap: .25rem;--_ui5-v2-5-0-tag-font-size: var(--sapFontSize);--_ui5-v2-5-0-tag-font: var(--sapFontSemiboldDuplexFamily);--_ui5-v2-5-0-tag-font-weight: normal;--_ui5-v2-5-0-tag-letter-spacing: normal;--_ui5-v2-5-0_bar_base_height: 2.75rem;--_ui5-v2-5-0_bar_subheader_height: 3rem;--_ui5-v2-5-0_bar-start-container-padding-start: 2rem;--_ui5-v2-5-0_bar-mid-container-padding-start-end: .5rem;--_ui5-v2-5-0_bar-end-container-padding-end: 2rem;--_ui5-v2-5-0_bar-start-container-padding-start_S: 1rem;--_ui5-v2-5-0_bar-start-container-padding-start_XL: 3rem;--_ui5-v2-5-0_bar-end-container-padding-end_S: 1rem;--_ui5-v2-5-0_bar-end-container-padding-end_XL: 3rem;--_ui5-v2-5-0_bar_subheader_margin-top: -.0625rem;--_ui5-v2-5-0_breadcrumbs_margin: 0 0 .5rem 0;--_ui5-v2-5-0_busy_indicator_block_layer: color-mix(in oklch, transparent, var(--sapBlockLayer_Background) 20%);--_ui5-v2-5-0_busy_indicator_color: var(--sapContent_BusyColor);--_ui5-v2-5-0_busy_indicator_focus_outline: var(--sapContent_FocusWidth) var(--sapContent_FocusStyle) var(--sapContent_FocusColor);--_ui5-v2-5-0-calendar-legend-root-padding: .75rem;--_ui5-v2-5-0-calendar-legend-root-width: 18.5rem;--_ui5-v2-5-0-calendar-legend-item-root-focus-margin: 0;--_ui5-v2-5-0-calendar-legend-item-root-width: 7.75rem;--_ui5-v2-5-0-calendar-legend-item-root-focus-border: var(--sapContent_FocusWidth) solid var(--sapContent_FocusColor);--_ui5-v2-5-0_card_box_shadow: var(--sapContent_Shadow0);--_ui5-v2-5-0_card_header_border_color: var(--sapTile_SeparatorColor);--_ui5-v2-5-0_card_header_focus_border: var(--sapContent_FocusWidth) var(--sapContent_FocusStyle) var(--sapContent_FocusColor);--_ui5-v2-5-0_card_header_focus_bottom_radius: 0px;--_ui5-v2-5-0_card_header_title_font_weight: normal;--_ui5-v2-5-0_card_header_subtitle_margin_top: .25rem;--_ui5-v2-5-0_card_hover_box_shadow: var(--sapContent_Shadow2);--_ui5-v2-5-0_card_header_focus_offset: 0px;--_ui5-v2-5-0_card_header_focus_radius: var(--_ui5-v2-5-0_card_border-radius);--_ui5-v2-5-0_card_header_title_font_family: var(--sapFontHeaderFamily);--_ui5-v2-5-0_card_header_title_font_size: var(--sapFontHeader6Size);--_ui5-v2-5-0_card_header_hover_bg: var(--sapTile_Hover_Background);--_ui5-v2-5-0_card_header_active_bg: var(--sapTile_Active_Background);--_ui5-v2-5-0_card_header_border: none;--_ui5-v2-5-0_card_border-radius: var(--sapTile_BorderCornerRadius);--_ui5-v2-5-0_card_header_padding: 1rem 1rem .75rem 1rem;--_ui5-v2-5-0_card_border: none;--ui5-v2-5-0_carousel_background_color_solid: var(--sapGroup_ContentBackground);--ui5-v2-5-0_carousel_background_color_translucent: var(--sapBackgroundColor);--ui5-v2-5-0_carousel_button_size: 2.5rem;--ui5-v2-5-0_carousel_inactive_dot_size: .25rem;--ui5-v2-5-0_carousel_inactive_dot_margin: 0 .375rem;--ui5-v2-5-0_carousel_inactive_dot_border: 1px solid var(--sapContent_ForegroundBorderColor);--ui5-v2-5-0_carousel_inactive_dot_background: var(--sapContent_ForegroundBorderColor);--ui5-v2-5-0_carousel_active_dot_border: 1px solid var(--sapContent_Selected_ForegroundColor);--ui5-v2-5-0_carousel_active_dot_background: var(--sapContent_Selected_ForegroundColor);--ui5-v2-5-0_carousel_navigation_button_active_box_shadow: none;--_ui5-v2-5-0_checkbox_box_shadow: none;--_ui5-v2-5-0_checkbox_transition: unset;--_ui5-v2-5-0_checkbox_focus_border: none;--_ui5-v2-5-0_checkbox_border_radius: 0;--_ui5-v2-5-0_checkbox_focus_outline: var(--sapContent_FocusWidth) var(--sapContent_FocusStyle) var(--sapContent_FocusColor);--_ui5-v2-5-0_checkbox_outer_hover_background: transparent;--_ui5-v2-5-0_checkbox_inner_width_height: 1.375rem;--_ui5-v2-5-0_checkbox_inner_disabled_border_color: var(--sapField_BorderColor);--_ui5-v2-5-0_checkbox_inner_information_box_shadow: none;--_ui5-v2-5-0_checkbox_inner_warning_box_shadow: none;--_ui5-v2-5-0_checkbox_inner_error_box_shadow: none;--_ui5-v2-5-0_checkbox_inner_success_box_shadow: none;--_ui5-v2-5-0_checkbox_inner_default_box_shadow: none;--_ui5-v2-5-0_checkbox_inner_background: var(--sapField_Background);--_ui5-v2-5-0_checkbox_wrapped_focus_padding: .375rem;--_ui5-v2-5-0_checkbox_wrapped_focus_inset_block: var(--_ui5-v2-5-0_checkbox_focus_position);--_ui5-v2-5-0_checkbox_compact_wrapper_padding: .5rem;--_ui5-v2-5-0_checkbox_compact_width_height: 2rem;--_ui5-v2-5-0_checkbox_compact_inner_size: 1rem;--_ui5-v2-5-0_checkbox_compact_focus_position: .375rem;--_ui5-v2-5-0_checkbox_label_offset: var(--_ui5-v2-5-0_checkbox_wrapper_padding);--_ui5-v2-5-0_checkbox_disabled_label_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_checkbox_default_focus_border: none;--_ui5-v2-5-0_checkbox_focus_outline_display: block;--_ui5-v2-5-0_checkbox_wrapper_padding: .6875rem;--_ui5-v2-5-0_checkbox_width_height: 2.75rem;--_ui5-v2-5-0_checkbox_label_color: var(--sapField_TextColor);--_ui5-v2-5-0_checkbox_inner_border: solid var(--sapField_BorderWidth) var(--sapField_BorderColor);--_ui5-v2-5-0_checkbox_inner_border_radius: var(--sapField_BorderCornerRadius);--_ui5-v2-5-0_checkbox_checkmark_color: var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_checkbox_hover_background: var(--sapContent_Selected_Hover_Background);--_ui5-v2-5-0_checkbox_inner_hover_border_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_checkbox_inner_hover_checked_border_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_checkbox_inner_selected_border_color: var(--sapField_BorderColor);--_ui5-v2-5-0_checkbox_inner_active_border_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_checkbox_active_background: var(--sapContent_Selected_Hover_Background);--_ui5-v2-5-0_checkbox_inner_readonly_border: var(--sapElement_BorderWidth) var(--sapField_ReadOnly_BorderColor) dashed;--_ui5-v2-5-0_checkbox_inner_error_border: var(--sapField_InvalidBorderWidth) solid var(--sapField_InvalidColor);--_ui5-v2-5-0_checkbox_inner_error_background_hover: var(--sapField_Hover_Background);--_ui5-v2-5-0_checkbox_inner_warning_border: var(--sapField_WarningBorderWidth) solid var(--sapField_WarningColor);--_ui5-v2-5-0_checkbox_inner_warning_color: var(--sapField_WarningColor);--_ui5-v2-5-0_checkbox_inner_warning_background_hover: var(--sapField_Hover_Background);--_ui5-v2-5-0_checkbox_checkmark_warning_color: var(--sapField_WarningColor);--_ui5-v2-5-0_checkbox_inner_success_border: var(--sapField_SuccessBorderWidth) solid var(--sapField_SuccessColor);--_ui5-v2-5-0_checkbox_inner_success_background_hover: var(--sapField_Hover_Background);--_ui5-v2-5-0_checkbox_inner_information_color: var(--sapField_InformationColor);--_ui5-v2-5-0_checkbox_inner_information_border: var(--sapField_InformationBorderWidth) solid var(--sapField_InformationColor);--_ui5-v2-5-0_checkbox_inner_information_background_hover: var(--sapField_Hover_Background);--_ui5-v2-5-0_checkbox_disabled_opacity: var(--sapContent_DisabledOpacity);--_ui5-v2-5-0_checkbox_focus_position: .3125rem;--_ui5-v2-5-0_checkbox_focus_border_radius: .5rem;--_ui5-v2-5-0_checkbox_right_focus_distance: var(--_ui5-v2-5-0_checkbox_focus_position);--_ui5-v2-5-0_color-palette-item-after-focus-inset: .0625rem;--_ui5-v2-5-0_color-palette-item-outer-border-radius: .25rem;--_ui5-v2-5-0_color-palette-item-inner-border-radius: .1875rem;--_ui5-v2-5-0_color-palette-item-after-not-focus-color: .0625rem solid var(--sapGroup_ContentBackground);--_ui5-v2-5-0_color-palette-item-container-sides-padding: .3125rem;--_ui5-v2-5-0_color-palette-item-container-rows-padding: .6875rem;--_ui5-v2-5-0_color-palette-item-focus-height: 1.5rem;--_ui5-v2-5-0_color-palette-item-container-padding: var(--_ui5-v2-5-0_color-palette-item-container-sides-padding) var(--_ui5-v2-5-0_color-palette-item-container-rows-padding);--_ui5-v2-5-0_color-palette-item-hover-margin: .0625rem;--_ui5-v2-5-0_color-palette-row-height: 9.5rem;--_ui5-v2-5-0_color-palette-button-height: 3rem;--_ui5-v2-5-0_color-palette-item-before-focus-color: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_color-palette-item-before-focus-inset: -.3125rem;--_ui5-v2-5-0_color-palette-item-before-focus-hover-inset: -.0625rem;--_ui5-v2-5-0_color-palette-item-after-focus-color: .0625rem solid var(--sapContent_ContrastFocusColor);--_ui5-v2-5-0_color-palette-item-selected-focused-border-after: none;--_ui5-v2-5-0_color-palette-item-after-focus-hover-inset: .0625rem;--_ui5-v2-5-0_color-palette-item-before-focus-border-radius: .4375rem;--_ui5-v2-5-0_color-palette-item-after-focus-border-radius: .3125rem;--_ui5-v2-5-0_color-palette-item-hover-outer-border-radius: .4375rem;--_ui5-v2-5-0_color-palette-item-hover-inner-border-radius: .375rem;--_ui5-v2-5-0_color-palette-item-selected-focused-border-before: -.0625rem;--_ui5-v2-5-0_color-palette-item-after-focus-not-selected-border: none;--_ui5-v2-5-0_color-palette-item-selected-focused-border: none;--_ui5-v2-5-0_color-palette-item-mobile-focus-sides-inset: -.375rem -.375rem;--_ui5-v2-5-0-color-palette-item-mobile-focus-inset: 0px;--_ui5-v2-5-0_color-palette-item-after-mobile-focus-border: none;--_ui5-v2-5-0_color_picker_circle_outer_border: .0625rem solid var(--sapContent_ContrastShadowColor);--_ui5-v2-5-0_color_picker_circle_inner_border: .0625rem solid var(--sapField_BorderColor);--_ui5-v2-5-0_color_picker_circle_inner_circle_size: .5625rem;--_ui5-v2-5-0_color_picker_slider_handle_box_shadow: .125rem solid var(--sapField_BorderColor);--_ui5-v2-5-0_color_picker_slider_handle_border: .125rem solid var(--sapField_BorderColor);--_ui5-v2-5-0_color_picker_slider_handle_outline_hover: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_color_picker_slider_handle_outline_focus: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_color_picker_slider_handle_margin_top: -.1875rem;--_ui5-v2-5-0_color_picker_slider_handle_focus_margin_top: var(--_ui5-v2-5-0_color_picker_slider_handle_margin_top);--_ui5-v2-5-0_color_picker_slider_container_margin_top: -11px;--_ui5-v2-5-0_color_picker_slider_handle_inline_focus: 1px solid var(--sapContent_ContrastFocusColor);--_ui5-v2-5-0_datepicker_icon_border: none;--_ui5-v2-5-0-datepicker-hover-background: var(--sapField_Hover_Background);--_ui5-v2-5-0-datepicker_border_radius: .25rem;--_ui5-v2-5-0-datepicker_icon_border_radius: .125rem;--_ui5-v2-5-0_daypicker_item_box_shadow: inset 0 0 0 .0625rem var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_daypicker_item_margin: 2px;--_ui5-v2-5-0_daypicker_item_border: none;--_ui5-v2-5-0_daypicker_item_selected_border_color: var(--sapList_Background);--_ui5-v2-5-0_daypicker_daynames_container_height: 2rem;--_ui5-v2-5-0_daypicker_weeknumbers_container_padding_top: 2rem;--_ui5-v2-5-0_daypicker_item_othermonth_background_color: var(--sapList_Background);--_ui5-v2-5-0_daypicker_item_othermonth_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_daypicker_item_othermonth_hover_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_daypicker_item_now_inner_border_radius: 0;--_ui5-v2-5-0_daypicker_item_outline_width: 1px;--_ui5-v2-5-0_daypicker_item_outline_offset: 1px;--_ui5-v2-5-0_daypicker_item_now_focus_after_width: calc(100% - .25rem) ;--_ui5-v2-5-0_daypicker_item_now_focus_after_height: calc(100% - .25rem) ;--_ui5-v2-5-0_daypicker_item_now_selected_focus_after_width: calc(100% - .375rem) ;--_ui5-v2-5-0_daypicker_item_now_selected_focus_after_height: calc(100% - .375rem) ;--_ui5-v2-5-0_daypicker_item_selected_background: transparent;--_ui5-v2-5-0_daypicker_item_outline_focus_after: none;--_ui5-v2-5-0_daypicker_item_border_focus_after: var(--_ui5-v2-5-0_daypicker_item_outline_width) dotted var(--sapContent_FocusColor);--_ui5-v2-5-0_daypicker_item_width_focus_after: calc(100% - .25rem) ;--_ui5-v2-5-0_daypicker_item_height_focus_after: calc(100% - .25rem) ;--_ui5-v2-5-0_daypicker_item_now_outline: none;--_ui5-v2-5-0_daypicker_item_now_outline_offset: none;--_ui5-v2-5-0_daypicker_item_now_outline_offset_focus_after: var(--_ui5-v2-5-0_daypicker_item_now_outline_offset);--_ui5-v2-5-0_daypicker_item_selected_between_hover_background: var(--sapList_Hover_SelectionBackground);--_ui5-v2-5-0_daypicker_item_now_not_selected_inset: 0;--_ui5-v2-5-0_daypicker_item_now_border_color: var(--sapLegend_CurrentDateTime);--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_border_radios: .25rem;--_ui5-v2-5-0_daypicker_special_day_top: 2.5rem;--_ui5-v2-5-0_daypicker_special_day_before_border_color: var(--sapList_Background);--_ui5-v2-5-0_daypicker_selected_item_now_special_day_border_bottom_radius: 0;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_after_border_width: .125rem;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_dot: .375rem;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_top: 2rem;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_right: 1.4375rem;--_ui5-v2-5-0_daypicker_item_border_radius: .4375rem;--_ui5-v2-5-0_daypicker_item_focus_border: .0625rem dotted var(--sapContent_FocusColor);--_ui5-v2-5-0_daypicker_item_selected_border: .0625rem solid var(--sapList_SelectionBorderColor);--_ui5-v2-5-0_daypicker_item_not_selected_focus_border: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_daypicker_item_selected_focus_color: var(--sapContent_FocusColor);--_ui5-v2-5-0_daypicker_item_selected_focus_width: .125rem;--_ui5-v2-5-0_daypicker_item_no_selected_inset: .375rem;--_ui5-v2-5-0_daypicker_item_now_border_focus_after: .125rem solid var(--sapList_SelectionBorderColor);--_ui5-v2-5-0_daypicker_item_now_border_radius_focus_after: .3125rem;--_ui5-v2-5-0_day_picker_item_selected_now_border_focus: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_day_picker_item_selected_now_border_radius_focus: .1875rem;--ui5-v2-5-0-dp-item_withsecondtype_border: .375rem;--_ui5-v2-5-0_daypicker_item_now_border: .125rem solid var(--sapLegend_CurrentDateTime);--_ui5-v2-5-0_daypicker_dayname_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_daypicker_weekname_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_daypicker_item_selected_box_shadow: inset 0 0 0 .0625rem var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_daypicker_item_selected_daytext_hover_background: transparent;--_ui5-v2-5-0_daypicker_item_border_radius_item: .5rem;--_ui5-v2-5-0_daypicker_item_border_radius_focus_after: .1875rem;--_ui5-v2-5-0_daypicker_item_selected_between_border: .5rem;--_ui5-v2-5-0_daypicker_item_selected_between_background: var(--sapList_SelectionBackgroundColor);--_ui5-v2-5-0_daypicker_item_selected_between_text_background: transparent;--_ui5-v2-5-0_daypicker_item_selected_between_text_font: var(--sapFontFamily);--_ui5-v2-5-0_daypicker_item_selected_text_font: var(--sapFontBoldFamily);--_ui5-v2-5-0_daypicker_item_now_box_shadow: inset 0 0 0 .35rem var(--sapList_Background);--_ui5-v2-5-0_daypicker_item_selected_text_outline: .0625rem solid var(--sapSelectedColor);--_ui5-v2-5-0_daypicker_item_now_selected_outline_offset: -.25rem;--_ui5-v2-5-0_daypicker_item_now_selected_between_inset: .25rem;--_ui5-v2-5-0_daypicker_item_now_selected_between_border: .0625rem solid var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_daypicker_item_now_selected_between_border_radius: .1875rem;--_ui5-v2-5-0_daypicker_item_select_between_border: 1px solid var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_daypicker_item_weeekend_filter: brightness(105%);--_ui5-v2-5-0_daypicker_item_selected_hover: var(--sapList_Hover_Background);--_ui5-v2-5-0_daypicker_item_now_inset: .3125rem;--_ui5-v2-5-0-dp-item_withsecondtype_border: .25rem;--_ui5-v2-5-0_daypicker_item_selected__secondary_type_text_outline: .0625rem solid var(--sapSelectedColor);--_ui5-v2-5-0_daypicker_two_calendar_item_now_day_text_content: "";--_ui5-v2-5-0_daypicker_two_calendar_item_now_selected_border_width: .125rem;--_ui5-v2-5-0_daypicker_two_calendar_item_border_radius: .5rem;--_ui5-v2-5-0_daypicker_two_calendar_item_border_focus_border_radius: .375rem;--_ui5-v2-5-0_daypicker_two_calendar_item_no_selected_inset: 0;--_ui5-v2-5-0_daypicker_two_calendar_item_selected_now_border_radius_focus: .1875rem;--_ui5-v2-5-0_daypicker_two_calendar_item_no_selected_focus_inset: .1875rem;--_ui5-v2-5-0_daypicker_two_calendar_item_no_select_focus_border_radius: .3125rem;--_ui5-v2-5-0_daypicker_two_calendar_item_now_inset: .3125rem;--_ui5-v2-5-0_daypicker_two_calendar_item_now_selected_border_inset: .125rem;--_ui5-v2-5-0_daypicker_selected_item_special_day_width: calc(100% - .125rem) ;--_ui5-v2-5-0_daypicker_special_day_border_bottom_radius: .5rem;--_ui5-v2-5-0-daypicker_item_selected_now_border_radius: .5rem;--_ui5-v2-5-0_daypicker_selected_item_now_special_day_width: calc(100% - .1875rem) ;--_ui5-v2-5-0_daypicker_selected_item_now_special_day_border_bottom_radius_alternate: .5rem;--_ui5-v2-5-0_daypicker_selected_item_now_special_day_top: 2.4375rem;--_ui5-v2-5-0_daypicker_two_calendar_item_margin_bottom: 0;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_now_inset: .3125rem;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_now_border_radius: .25rem;--_ui5-v2-5-0_daypicker_item_now_focus_margin: 0;--_ui5-v2-5-0_daypicker_special_day_border_top: none;--_ui5-v2-5-0_daypicker_special_day_selected_border_radius_bottom: .25rem;--_ui5-v2-5-0_daypicker_specialday_focused_top: 2.125rem;--_ui5-v2-5-0_daypicker_specialday_focused_width: calc(100% - .75rem) ;--_ui5-v2-5-0_daypicker_specialday_focused_border_bottom: 0;--_ui5-v2-5-0_daypicker_item_now_specialday_top: 2.3125rem;--_ui5-v2-5-0_daypicker_item_now_specialday_width: calc(100% - .5rem) ;--_ui5-v2-5-0_dialog_header_error_state_icon_color: var(--sapNegativeElementColor);--_ui5-v2-5-0_dialog_header_information_state_icon_color: var(--sapInformativeElementColor);--_ui5-v2-5-0_dialog_header_success_state_icon_color: var(--sapPositiveElementColor);--_ui5-v2-5-0_dialog_header_warning_state_icon_color: var(--sapCriticalElementColor);--_ui5-v2-5-0_dialog_header_state_line_height: .0625rem;--_ui5-v2-5-0_dialog_header_focus_bottom_offset: 2px;--_ui5-v2-5-0_dialog_header_focus_top_offset: 1px;--_ui5-v2-5-0_dialog_header_focus_left_offset: 1px;--_ui5-v2-5-0_dialog_header_focus_right_offset: 1px;--_ui5-v2-5-0_dialog_header_border_radius: var(--sapElement_BorderCornerRadius);--_ui5-v2-5-0_file_uploader_value_state_error_hover_background_color: var(--sapField_Hover_Background);--_ui5-v2-5-0_file_uploader_hover_border: none;--_ui5-v2-5-0_table_cell_valign: center;--_ui5-v2-5-0_table_cell_min_width: 2.75rem;--_ui5-v2-5-0_table_navigated_cell_width: .1875rem;--_ui5-v2-5-0_table_shadow_border_left: inset var(--sapContent_FocusWidth) 0 var(--sapContent_FocusColor);--_ui5-v2-5-0_table_shadow_border_right: inset calc(-1 * var(--sapContent_FocusWidth)) 0 var(--sapContent_FocusColor);--_ui5-v2-5-0_table_shadow_border_top: inset 0 var(--sapContent_FocusWidth) var(--sapContent_FocusColor);--_ui5-v2-5-0_table_shadow_border_bottom: inset 0 -1px var(--sapContent_FocusColor);--ui5-v2-5-0-form-item-layout: 4fr 8fr 0fr;--ui5-v2-5-0-form-item-label-justify: end;--ui5-v2-5-0-form-item-label-justify-span12: start;--ui5-v2-5-0-form-item-label-padding: .125rem 0;--ui5-v2-5-0-form-item-label-padding-end: .85rem;--ui5-v2-5-0-form-item-label-padding-span12: .625rem .25rem 0 .25rem;--ui5-v2-5-0-group-header-listitem-background-color: var(--sapList_GroupHeaderBackground);--ui5-v2-5-0-icon-focus-border-radius: .25rem;--_ui5-v2-5-0_input_width: 13.125rem;--_ui5-v2-5-0_input_min_width: 2.75rem;--_ui5-v2-5-0_input_height: var(--sapElement_Height);--_ui5-v2-5-0_input_compact_height: 1.625rem;--_ui5-v2-5-0_input_value_state_error_hover_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_input_background_color: var(--sapField_Background);--_ui5-v2-5-0_input_border_radius: var(--sapField_BorderCornerRadius);--_ui5-v2-5-0_input_placeholder_style: italic;--_ui5-v2-5-0_input_placeholder_color: var(--sapField_PlaceholderTextColor);--_ui5-v2-5-0_input_bottom_border_height: 0;--_ui5-v2-5-0_input_bottom_border_color: transparent;--_ui5-v2-5-0_input_focused_border_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_input_state_border_width: .125rem;--_ui5-v2-5-0_input_information_border_width: .125rem;--_ui5-v2-5-0_input_error_font_weight: normal;--_ui5-v2-5-0_input_warning_font_weight: normal;--_ui5-v2-5-0_input_focus_border_width: 1px;--_ui5-v2-5-0_input_error_warning_font_style: inherit;--_ui5-v2-5-0_input_error_warning_text_indent: 0;--_ui5-v2-5-0_input_disabled_color: var(--sapContent_DisabledTextColor);--_ui5-v2-5-0_input_disabled_font_weight: normal;--_ui5-v2-5-0_input_disabled_border_color: var(--sapField_BorderColor);--_ui5-v2-5-0-input_disabled_background: var(--sapField_Background);--_ui5-v2-5-0_input_readonly_border_color: var(--sapField_ReadOnly_BorderColor);--_ui5-v2-5-0_input_readonly_background: var(--sapField_ReadOnly_Background);--_ui5-v2-5-0_input_disabled_opacity: var(--sapContent_DisabledOpacity);--_ui5-v2-5-0_input_icon_min_width: 2.25rem;--_ui5-v2-5-0_input_compact_min_width: 2rem;--_ui5-v2-5-0_input_transition: none;--_ui5-v2-5-0-input-value-state-icon-display: none;--_ui5-v2-5-0_input_value_state_error_border_color: var(--sapField_InvalidColor);--_ui5-v2-5-0_input_focused_value_state_error_border_color: var(--sapField_InvalidColor);--_ui5-v2-5-0_input_value_state_warning_border_color: var(--sapField_WarningColor);--_ui5-v2-5-0_input_focused_value_state_warning_border_color: var(--sapField_WarningColor);--_ui5-v2-5-0_input_value_state_success_border_color: var(--sapField_SuccessColor);--_ui5-v2-5-0_input_focused_value_state_success_border_color: var(--sapField_SuccessColor);--_ui5-v2-5-0_input_value_state_success_border_width: 1px;--_ui5-v2-5-0_input_value_state_information_border_color: var(--sapField_InformationColor);--_ui5-v2-5-0_input_focused_value_state_information_border_color: var(--sapField_InformationColor);--_ui5-v2-5-0-input-value-state-information-border-width: 1px;--_ui5-v2-5-0-input-background-image: none;--ui5-v2-5-0_input_focus_pseudo_element_content: "";--_ui5-v2-5-0_input_value_state_error_warning_placeholder_font_weight: normal;--_ui5-v2-5-0-input_error_placeholder_color: var(--sapField_PlaceholderTextColor);--_ui5-v2-5-0_input_icon_width: 2.25rem;--_ui5-v2-5-0-input-icons-count: 0;--_ui5-v2-5-0_input_margin_top_bottom: .1875rem;--_ui5-v2-5-0_input_tokenizer_min_width: 3.25rem;--_ui5-v2-5-0-input-border: none;--_ui5-v2-5-0_input_hover_border: none;--_ui5-v2-5-0_input_focus_border_radius: .25rem;--_ui5-v2-5-0_input_readonly_focus_border_radius: .125rem;--_ui5-v2-5-0_input_error_warning_border_style: none;--_ui5-v2-5-0_input_focused_value_state_error_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_input_focused_value_state_warning_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_input_focused_value_state_success_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_input_focused_value_state_information_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_input_focused_value_state_error_focus_outline_color: var(--sapField_InvalidColor);--_ui5-v2-5-0_input_focused_value_state_warning_focus_outline_color: var(--sapField_WarningColor);--_ui5-v2-5-0_input_focused_value_state_success_focus_outline_color: var(--sapField_SuccessColor);--_ui5-v2-5-0_input_focus_offset: 0;--_ui5-v2-5-0_input_readonly_focus_offset: .125rem;--_ui5-v2-5-0_input_information_icon_padding: .625rem .625rem .5rem .625rem;--_ui5-v2-5-0_input_information_focused_icon_padding: .625rem .625rem .5625rem .625rem;--_ui5-v2-5-0_input_error_warning_icon_padding: .625rem .625rem .5rem .625rem;--_ui5-v2-5-0_input_error_warning_focused_icon_padding: .625rem .625rem .5625rem .625rem;--_ui5-v2-5-0_input_custom_icon_padding: .625rem .625rem .5625rem .625rem;--_ui5-v2-5-0_input_error_warning_custom_icon_padding: .625rem .625rem .5rem .625rem;--_ui5-v2-5-0_input_error_warning_custom_focused_icon_padding: .625rem .625rem .5625rem .625rem;--_ui5-v2-5-0_input_information_custom_icon_padding: .625rem .625rem .5rem .625rem;--_ui5-v2-5-0_input_information_custom_focused_icon_padding: .625rem .625rem .5625rem .625rem;--_ui5-v2-5-0_input_focus_outline_color: var(--sapField_Active_BorderColor);--_ui5-v2-5-0_input_icon_wrapper_height: calc(100% - 1px) ;--_ui5-v2-5-0_input_icon_wrapper_state_height: calc(100% - 2px) ;--_ui5-v2-5-0_input_icon_wrapper_success_state_height: calc(100% - var(--_ui5-v2-5-0_input_value_state_success_border_width));--_ui5-v2-5-0_input_icon_color: var(--sapContent_IconColor);--_ui5-v2-5-0_input_icon_pressed_bg: var(--sapButton_Selected_Background);--_ui5-v2-5-0_input_icon_padding: .625rem .625rem .5625rem .625rem;--_ui5-v2-5-0_input_icon_hover_bg: var(--sapField_Focus_Background);--_ui5-v2-5-0_input_icon_pressed_color: var(--sapButton_Active_TextColor);--_ui5-v2-5-0_input_icon_border_radius: .25rem;--_ui5-v2-5-0_input_icon_box_shadow: var(--sapField_Hover_Shadow);--_ui5-v2-5-0_input_icon_border: none;--_ui5-v2-5-0_input_error_icon_box_shadow: var(--sapContent_Negative_Shadow);--_ui5-v2-5-0_input_warning_icon_box_shadow: var(--sapContent_Critical_Shadow);--_ui5-v2-5-0_input_information_icon_box_shadow: var(--sapContent_Informative_Shadow);--_ui5-v2-5-0_input_success_icon_box_shadow: var(--sapContent_Positive_Shadow);--_ui5-v2-5-0_input_icon_error_pressed_color: var(--sapButton_Reject_Selected_TextColor);--_ui5-v2-5-0_input_icon_warning_pressed_color: var(--sapButton_Attention_Selected_TextColor);--_ui5-v2-5-0_input_icon_information_pressed_color: var(--sapButton_Selected_TextColor);--_ui5-v2-5-0_input_icon_success_pressed_color: var(--sapButton_Accept_Selected_TextColor);--_ui5-v2-5-0_link_focus_text_decoration: underline;--_ui5-v2-5-0_link_text_decoration: var(--sapLink_TextDecoration);--_ui5-v2-5-0_link_hover_text_decoration: var(--sapLink_Hover_TextDecoration);--_ui5-v2-5-0_link_focused_hover_text_decoration: none;--_ui5-v2-5-0_link_focused_hover_text_color: var(--sapContent_ContrastTextColor);--_ui5-v2-5-0_link_active_text_decoration: var(--sapLink_Active_TextDecoration);--_ui5-v2-5-0_link_outline: none;--_ui5-v2-5-0_link_focus_border-radius: .125rem;--_ui5-v2-5-0_link_focus_background_color: var(--sapContent_FocusColor);--_ui5-v2-5-0_link_focus_color: var(--sapContent_ContrastTextColor);--_ui5-v2-5-0_link_subtle_text_decoration: underline;--_ui5-v2-5-0_link_subtle_text_decoration_hover: none;--ui5-v2-5-0_list_footer_text_color: var(--sapList_FooterTextColor);--ui5-v2-5-0-listitem-background-color: var(--sapList_Background);--ui5-v2-5-0-listitem-border-bottom: var(--sapList_BorderWidth) solid var(--sapList_BorderColor);--ui5-v2-5-0-listitem-selected-border-bottom: 1px solid var(--sapList_SelectionBorderColor);--ui5-v2-5-0-listitem-focused-selected-border-bottom: 1px solid var(--sapList_SelectionBorderColor);--_ui5-v2-5-0_listitembase_focus_width: 1px;--_ui5-v2-5-0-listitembase_disabled_opacity: .5;--_ui5-v2-5-0_product_switch_item_border: none;--ui5-v2-5-0-listitem-active-border-color: var(--sapContent_FocusColor);--_ui5-v2-5-0_menu_item_padding: 0 1rem 0 .75rem;--_ui5-v2-5-0_menu_item_submenu_icon_right: 1rem;--_ui5-v2-5-0_menu_item_additional_text_start_margin: 1rem;--_ui5-v2-5-0_menu_popover_border_radius: var(--sapPopover_BorderCornerRadius);--_ui5-v2-5-0_monthpicker_item_margin: .0625rem;--_ui5-v2-5-0_monthpicker_item_border: .0625rem solid var(--sapButton_Lite_BorderColor);--_ui5-v2-5-0_monthpicker_item_hover_border: .0625rem solid var(--sapButton_Lite_Hover_BorderColor);--_ui5-v2-5-0_monthpicker_item_active_border: .0625rem solid var(--sapButton_Lite_Active_BorderColor);--_ui5-v2-5-0_monthpicker_item_selected_border: .0625rem solid var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_monthpicker_item_selected_hover_border: .0625rem solid var(--sapButton_Selected_Hover_BorderColor);--_ui5-v2-5-0_monthpicker_item_border_radius: .5rem;--_ui5-v2-5-0_message_strip_icon_width: 2.5rem;--_ui5-v2-5-0_message_strip_button_border_width: 0;--_ui5-v2-5-0_message_strip_button_border_style: none;--_ui5-v2-5-0_message_strip_button_border_color: transparent;--_ui5-v2-5-0_message_strip_button_border_radius: 0;--_ui5-v2-5-0_message_strip_padding: .4375rem 2.5rem .4375rem 2.5rem;--_ui5-v2-5-0_message_strip_padding_block_no_icon: .4375rem .4375rem;--_ui5-v2-5-0_message_strip_padding_inline_no_icon: 1rem 2.5rem;--_ui5-v2-5-0_message_strip_button_height: 1.625rem;--_ui5-v2-5-0_message_strip_border_width: 1px;--_ui5-v2-5-0_message_strip_close_button_border: none;--_ui5-v2-5-0_message_strip_icon_top: .4375rem;--_ui5-v2-5-0_message_strip_focus_width: 1px;--_ui5-v2-5-0_message_strip_focus_offset: -2px;--_ui5-v2-5-0_message_strip_close_button_top: .125rem;--_ui5-v2-5-0_message_strip_close_button_color_set_1_background: #eaecee4d;--_ui5-v2-5-0_message_strip_close_button_color_set_2_background: #eaecee80;--_ui5-v2-5-0_message_strip_close_button_color_set_1_color: var(--sapButton_Emphasized_TextColor);--_ui5-v2-5-0_message_strip_close_button_color_set_1_hover_color: var(--sapButton_Emphasized_TextColor);--_ui5-v2-5-0_message_strip_scheme_1_set_2_background: var(--sapIndicationColor_1b);--_ui5-v2-5-0_message_strip_scheme_1_set_2_border_color: var(--sapIndicationColor_1b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_2_set_2_background: var(--sapIndicationColor_2b);--_ui5-v2-5-0_message_strip_scheme_2_set_2_border_color: var(--sapIndicationColor_2b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_3_set_2_background: var(--sapIndicationColor_3b);--_ui5-v2-5-0_message_strip_scheme_3_set_2_border_color: var(--sapIndicationColor_3b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_4_set_2_background: var(--sapIndicationColor_4b);--_ui5-v2-5-0_message_strip_scheme_4_set_2_border_color: var(--sapIndicationColor_4b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_5_set_2_background: var(--sapIndicationColor_5b);--_ui5-v2-5-0_message_strip_scheme_5_set_2_border_color: var(--sapIndicationColor_5b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_6_set_2_background: var(--sapIndicationColor_6b);--_ui5-v2-5-0_message_strip_scheme_6_set_2_border_color: var(--sapIndicationColor_6b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_7_set_2_background: var(--sapIndicationColor_7b);--_ui5-v2-5-0_message_strip_scheme_7_set_2_border_color: var(--sapIndicationColor_7b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_8_set_2_background: var(--sapIndicationColor_8b);--_ui5-v2-5-0_message_strip_scheme_8_set_2_border_color: var(--sapIndicationColor_8b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_9_set_2_background: var(--sapIndicationColor_9b);--_ui5-v2-5-0_message_strip_scheme_9_set_2_border_color: var(--sapIndicationColor_9b_BorderColor);--_ui5-v2-5-0_message_strip_scheme_10_set_2_background: var(--sapIndicationColor_10b);--_ui5-v2-5-0_message_strip_scheme_10_set_2_border_color: var(--sapIndicationColor_10b_BorderColor);--_ui5-v2-5-0_message_strip_close_button_right: .1875rem;--_ui5-v2-5-0_panel_focus_border: var(--sapContent_FocusWidth) var(--sapContent_FocusStyle) var(--sapContent_FocusColor);--_ui5-v2-5-0_panel_header_height: 2.75rem;--_ui5-v2-5-0_panel_button_root_width: 2.75rem;--_ui5-v2-5-0_panel_button_root_height: 2.75rem;--_ui5-v2-5-0_panel_header_padding_right: .5rem;--_ui5-v2-5-0_panel_header_button_wrapper_padding: .25rem;--_ui5-v2-5-0_panel_border_radius: var(--sapElement_BorderCornerRadius);--_ui5-v2-5-0_panel_border_bottom: none;--_ui5-v2-5-0_panel_default_header_border: .0625rem solid var(--sapGroup_TitleBorderColor);--_ui5-v2-5-0_panel_outline_offset: -.125rem;--_ui5-v2-5-0_panel_border_radius_expanded: var(--sapElement_BorderCornerRadius) var(--sapElement_BorderCornerRadius) 0 0;--_ui5-v2-5-0_panel_icon_color: var(--sapButton_Lite_TextColor);--_ui5-v2-5-0_panel_focus_offset: 0px;--_ui5-v2-5-0_panel_focus_bottom_offset: -1px;--_ui5-v2-5-0_panel_content_padding: .625rem 1rem;--_ui5-v2-5-0_panel_header_background_color: var(--sapGroup_TitleBackground);--_ui5-v2-5-0_popover_background: var(--sapGroup_ContentBackground);--_ui5-v2-5-0_popover_box_shadow: var(--sapContent_Shadow2);--_ui5-v2-5-0_popover_no_arrow_box_shadow: var(--sapContent_Shadow1);--_ui5-v2-5-0_popup_content_padding_s: 1rem;--_ui5-v2-5-0_popup_content_padding_m_l: 2rem;--_ui5-v2-5-0_popup_content_padding_xl: 3rem;--_ui5-v2-5-0_popup_header_footer_padding_s: 1rem;--_ui5-v2-5-0_popup_header_footer_padding_m_l: 2rem;--_ui5-v2-5-0_popup_header_footer_padding_xl: 3rem;--_ui5-v2-5-0_popup_viewport_margin: 10px;--_ui5-v2-5-0_popup_header_font_weight: 400;--_ui5-v2-5-0_popup_header_prop_header_text_alignment: flex-start;--_ui5-v2-5-0_popup_header_background: var(--sapPageHeader_Background);--_ui5-v2-5-0_popup_header_shadow: var(--sapContent_HeaderShadow);--_ui5-v2-5-0_popup_header_border: none;--_ui5-v2-5-0_popup_border_radius: .5rem;--_ui5-v2-5-0_popup_block_layer_background: var(--sapBlockLayer_Background);--_ui5-v2-5-0_popup_block_layer_opacity: .2;--_ui5-v2-5-0_progress_indicator_bar_border_max: none;--_ui5-v2-5-0_progress_indicator_icon_visibility: inline-block;--_ui5-v2-5-0_progress_indicator_side_points_visibility: block;--_ui5-v2-5-0_progress_indicator_padding: 1.25rem 0 .75rem 0;--_ui5-v2-5-0_progress_indicator_padding_novalue: .3125rem;--_ui5-v2-5-0_progress_indicator_padding_end: 1.25rem;--_ui5-v2-5-0_progress_indicator_host_height: unset;--_ui5-v2-5-0_progress_indicator_host_min_height: unset;--_ui5-v2-5-0_progress_indicator_host_box_sizing: border-box;--_ui5-v2-5-0_progress_indicator_root_position: relative;--_ui5-v2-5-0_progress_indicator_root_border_radius: .25rem;--_ui5-v2-5-0_progress_indicator_root_height: .375rem;--_ui5-v2-5-0_progress_indicator_root_min_height: .375rem;--_ui5-v2-5-0_progress_indicator_root_overflow: visible;--_ui5-v2-5-0_progress_indicator_bar_height: .625rem;--_ui5-v2-5-0_progress_indicator_bar_border_radius: .5rem;--_ui5-v2-5-0_progress_indicator_remaining_bar_border_radius: .25rem;--_ui5-v2-5-0_progress_indicator_remaining_bar_position: absolute;--_ui5-v2-5-0_progress_indicator_remaining_bar_width: 100%;--_ui5-v2-5-0_progress_indicator_remaining_bar_overflow: visible;--_ui5-v2-5-0_progress_indicator_icon_position: absolute;--_ui5-v2-5-0_progress_indicator_icon_right_position: -1.25rem;--_ui5-v2-5-0_progress_indicator_value_margin: 0 0 .1875rem 0;--_ui5-v2-5-0_progress_indicator_value_position: absolute;--_ui5-v2-5-0_progress_indicator_value_top_position: -1.3125rem;--_ui5-v2-5-0_progress_indicator_value_left_position: 0;--_ui5-v2-5-0_progress_indicator_background_none: var(--sapProgress_Background);--_ui5-v2-5-0_progress_indicator_background_error: var(--sapProgress_NegativeBackground);--_ui5-v2-5-0_progress_indicator_background_warning: var(--sapProgress_CriticalBackground);--_ui5-v2-5-0_progress_indicator_background_success: var(--sapProgress_PositiveBackground);--_ui5-v2-5-0_progress_indicator_background_information: var(--sapProgress_InformationBackground);--_ui5-v2-5-0_progress_indicator_value_state_none: var(--sapProgress_Value_Background);--_ui5-v2-5-0_progress_indicator_value_state_error: var(--sapProgress_Value_NegativeBackground);--_ui5-v2-5-0_progress_indicator_value_state_warning: var(--sapProgress_Value_CriticalBackground);--_ui5-v2-5-0_progress_indicator_value_state_success: var(--sapProgress_Value_PositiveBackground);--_ui5-v2-5-0_progress_indicator_value_state_information: var(--sapProgress_Value_InformationBackground);--_ui5-v2-5-0_progress_indicator_value_state_error_icon_color: var(--sapProgress_Value_NegativeTextColor);--_ui5-v2-5-0_progress_indicator_value_state_warning_icon_color: var(--sapProgress_Value_CriticalTextColor);--_ui5-v2-5-0_progress_indicator_value_state_success_icon_color: var(--sapProgress_Value_PositiveTextColor);--_ui5-v2-5-0_progress_indicator_value_state_information_icon_color: var(--sapProgress_Value_InformationTextColor);--_ui5-v2-5-0_progress_indicator_border: none;--_ui5-v2-5-0_progress_indicator_border_color_error: var(--sapErrorBorderColor);--_ui5-v2-5-0_progress_indicator_border_color_warning: var(--sapWarningBorderColor);--_ui5-v2-5-0_progress_indicator_border_color_success: var(--sapSuccessBorderColor);--_ui5-v2-5-0_progress_indicator_border_color_information: var(--sapInformationBorderColor);--_ui5-v2-5-0_progress_indicator_color: var(--sapField_TextColor);--_ui5-v2-5-0_progress_indicator_bar_color: var(--sapProgress_TextColor);--_ui5-v2-5-0_progress_indicator_icon_size: var(--sapFontLargeSize);--_ui5-v2-5-0_rating_indicator_border_radius: .5rem;--_ui5-v2-5-0_rating_indicator_outline_offset: -.125rem;--_ui5-v2-5-0_rating_indicator_item_height: 1em;--_ui5-v2-5-0_rating_indicator_item_width: 1em;--_ui5-v2-5-0_rating_indicator_component_spacing: .5rem 0px;--_ui5-v2-5-0_rating_indicator_component_padding: .25rem;--_ui5-v2-5-0_rating_indicator_readonly_item_height: .75em;--_ui5-v2-5-0_rating_indicator_readonly_item_width: .75em;--_ui5-v2-5-0_rating_indicator_readonly_item_spacing: .1875rem .1875rem;--_ui5-v2-5-0_segmented_btn_inner_border: .0625rem solid transparent;--_ui5-v2-5-0_segmented_btn_inner_border_odd_child: .0625rem solid transparent;--_ui5-v2-5-0_segmented_btn_inner_pressed_border_odd_child: .0625rem solid var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_segmented_btn_inner_border_radius: var(--sapButton_BorderCornerRadius);--_ui5-v2-5-0_segmented_btn_background_color: var(--sapButton_Lite_Background);--_ui5-v2-5-0_segmented_btn_border_color: var(--sapButton_Lite_BorderColor);--_ui5-v2-5-0_segmented_btn_hover_box_shadow: none;--_ui5-v2-5-0_segmented_btn_item_border_left: .0625rem;--_ui5-v2-5-0_segmented_btn_item_border_right: .0625rem;--_ui5-v2-5-0_button_base_min_compact_width: 2rem;--_ui5-v2-5-0_button_base_height: var(--sapElement_Height);--_ui5-v2-5-0_button_compact_height: 1.625rem;--_ui5-v2-5-0_button_border_radius: var(--sapButton_BorderCornerRadius);--_ui5-v2-5-0_button_compact_padding: .4375rem;--_ui5-v2-5-0_button_emphasized_outline: 1px dotted var(--sapContent_FocusColor);--_ui5-v2-5-0_button_focus_offset: 1px;--_ui5-v2-5-0_button_focus_width: 1px;--_ui5-v2-5-0_button_emphasized_focused_border_before: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_button_emphasized_focused_active_border_color: transparent;--_ui5-v2-5-0_button_focused_border: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_button_focused_border_radius: .375rem;--_ui5-v2-5-0_button_focused_inner_border_radius: .375rem;--_ui5-v2-5-0_button_base_min_width: 2.25rem;--_ui5-v2-5-0_button_base_padding: .5625rem;--_ui5-v2-5-0_button_base_icon_only_padding: .5625rem;--_ui5-v2-5-0_button_base_icon_margin: .375rem;--_ui5-v2-5-0_button_icon_font_size: 1rem;--_ui5-v2-5-0_button_text_shadow: none;--_ui5-v2-5-0_button_emphasized_border_width: .0625rem;--_ui5-v2-5-0_button_pressed_focused_border_color: var(--sapContent_FocusColor);--_ui5-v2-5-0_button_fontFamily: var(--sapFontSemiboldDuplexFamily);--_ui5-v2-5-0_button_emphasized_focused_border_color: var(--sapContent_ContrastFocusColor);--_ui5-v2-5-0_radio_button_min_width: 2.75rem;--_ui5-v2-5-0_radio_button_hover_fill_error: var(--sapField_Hover_Background);--_ui5-v2-5-0_radio_button_hover_fill_warning: var(--sapField_Hover_Background);--_ui5-v2-5-0_radio_button_hover_fill_success: var(--sapField_Hover_Background);--_ui5-v2-5-0_radio_button_hover_fill_information: var(--sapField_Hover_Background);--_ui5-v2-5-0_radio_button_checked_fill: var(--sapSelectedColor);--_ui5-v2-5-0_radio_button_checked_error_fill: var(--sapField_InvalidColor);--_ui5-v2-5-0_radio_button_checked_success_fill: var(--sapField_SuccessColor);--_ui5-v2-5-0_radio_button_checked_information_fill: var(--sapField_InformationColor);--_ui5-v2-5-0_radio_button_warning_error_border_dash: 0;--_ui5-v2-5-0_radio_button_outer_ring_color: var(--sapField_BorderColor);--_ui5-v2-5-0_radio_button_outer_ring_width: var(--sapField_BorderWidth);--_ui5-v2-5-0_radio_button_outer_ring_bg: var(--sapField_Background);--_ui5-v2-5-0_radio_button_outer_ring_hover_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_radio_button_outer_ring_active_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_radio_button_outer_ring_checked_hover_color: var(--sapField_Hover_BorderColor);--_ui5-v2-5-0_radio_button_outer_ring_padding_with_label: 0 .6875rem;--_ui5-v2-5-0_radio_button_border: none;--_ui5-v2-5-0_radio_button_focus_outline: block;--_ui5-v2-5-0_radio_button_color: var(--sapField_BorderColor);--_ui5-v2-5-0_radio_button_label_offset: 1px;--_ui5-v2-5-0_radio_button_items_align: unset;--_ui5-v2-5-0_radio_button_information_border_width: var(--sapField_InformationBorderWidth);--_ui5-v2-5-0_radio_button_border_width: var(--sapContent_FocusWidth);--_ui5-v2-5-0_radio_button_border_radius: .5rem;--_ui5-v2-5-0_radio_button_label_color: var(--sapField_TextColor);--_ui5-v2-5-0_radio_button_inner_ring_radius: 27.5%;--_ui5-v2-5-0_radio_button_outer_ring_padding: 0 .6875rem;--_ui5-v2-5-0_radio_button_read_only_border_type: 4,2;--_ui5-v2-5-0_radio_button_inner_ring_color: var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_radio_button_checked_warning_fill: var(--sapField_WarningColor);--_ui5-v2-5-0_radio_button_read_only_inner_ring_color: var(--sapField_TextColor);--_ui5-v2-5-0_radio_button_read_only_border_width: var(--sapElement_BorderWidth);--_ui5-v2-5-0_radio_button_hover_fill: var(--sapContent_Selected_Hover_Background);--_ui5-v2-5-0_radio_button_focus_dist: .375rem;--_ui5-v2-5-0_switch_height: 2.75rem;--_ui5-v2-5-0_switch_foucs_border_size: 1px;--_ui5-v2-5-0-switch-root-border-radius: 0;--_ui5-v2-5-0-switch-root-box-shadow: none;--_ui5-v2-5-0-switch-focus: "";--_ui5-v2-5-0_switch_track_border_radius: .75rem;--_ui5-v2-5-0-switch-track-border: 1px solid;--_ui5-v2-5-0_switch_track_transition: none;--_ui5-v2-5-0_switch_handle_border_radius: 1rem;--_ui5-v2-5-0-switch-handle-icon-display: none;--_ui5-v2-5-0-switch-slider-texts-display: inline;--_ui5-v2-5-0_switch_width: 3.5rem;--_ui5-v2-5-0_switch_min_width: none;--_ui5-v2-5-0_switch_with_label_width: 3.875rem;--_ui5-v2-5-0_switch_focus_outline: none;--_ui5-v2-5-0_switch_root_after_outline: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_switch_root_after_boreder: none;--_ui5-v2-5-0_switch_root_after_boreder_radius: 1rem;--_ui5-v2-5-0_switch_root_outline_top: .5rem;--_ui5-v2-5-0_switch_root_outline_bottom: .5rem;--_ui5-v2-5-0_switch_root_outline_left: .375rem;--_ui5-v2-5-0_switch_root_outline_right: .375rem;--_ui5-v2-5-0_switch_disabled_opacity: var(--sapContent_DisabledOpacity);--_ui5-v2-5-0_switch_transform: translateX(100%) translateX(-1.625rem);--_ui5-v2-5-0_switch_transform_with_label: translateX(100%) translateX(-1.875rem);--_ui5-v2-5-0_switch_rtl_transform: translateX(-100%) translateX(1.625rem);--_ui5-v2-5-0_switch_rtl_transform_with_label: translateX(-100%) translateX(1.875rem);--_ui5-v2-5-0_switch_track_width: 2.5rem;--_ui5-v2-5-0_switch_track_height: 1.5rem;--_ui5-v2-5-0_switch_track_with_label_width: 2.875rem;--_ui5-v2-5-0_switch_track_with_label_height: 1.5rem;--_ui5-v2-5-0_switch_track_active_background_color: var(--sapButton_Track_Selected_Background);--_ui5-v2-5-0_switch_track_inactive_background_color: var(--sapButton_Track_Background);--_ui5-v2-5-0_switch_track_hover_active_background_color: var(--sapButton_Track_Selected_Hover_Background);--_ui5-v2-5-0_switch_track_hover_inactive_background_color: var(--sapButton_Track_Hover_Background);--_ui5-v2-5-0_switch_track_active_border_color: var(--sapButton_Track_Selected_BorderColor);--_ui5-v2-5-0_switch_track_inactive_border_color: var(--sapButton_Track_BorderColor);--_ui5-v2-5-0_switch_track_hover_active_border_color: var(--sapButton_Track_Selected_Hover_BorderColor);--_ui5-v2-5-0_switch_track_hover_inactive_border_color: var(--sapButton_Track_Hover_BorderColor);--_ui5-v2-5-0_switch_track_semantic_accept_background_color: var(--sapButton_Track_Positive_Background);--_ui5-v2-5-0_switch_track_semantic_reject_background_color: var(--sapButton_Track_Negative_Background);--_ui5-v2-5-0_switch_track_semantic_hover_accept_background_color: var(--sapButton_Track_Positive_Hover_Background);--_ui5-v2-5-0_switch_track_semantic_hover_reject_background_color: var(--sapButton_Track_Negative_Hover_Background);--_ui5-v2-5-0_switch_track_semantic_accept_border_color: var(--sapButton_Track_Positive_BorderColor);--_ui5-v2-5-0_switch_track_semantic_reject_border_color: var(--sapButton_Track_Negative_BorderColor);--_ui5-v2-5-0_switch_track_semantic_hover_accept_border_color: var(--sapButton_Track_Positive_Hover_BorderColor);--_ui5-v2-5-0_switch_track_semantic_hover_reject_border_color: var(--sapButton_Track_Negative_Hover_BorderColor);--_ui5-v2-5-0_switch_track_icon_display: inline-block;--_ui5-v2-5-0_switch_handle_width: 1.5rem;--_ui5-v2-5-0_switch_handle_height: 1.25rem;--_ui5-v2-5-0_switch_handle_with_label_width: 1.75rem;--_ui5-v2-5-0_switch_handle_with_label_height: 1.25rem;--_ui5-v2-5-0_switch_handle_border: var(--_ui5-v2-5-0_switch_handle_border_width) solid var(--sapButton_Handle_BorderColor);--_ui5-v2-5-0_switch_handle_border_width: .125rem;--_ui5-v2-5-0_switch_handle_active_background_color: var(--sapButton_Handle_Selected_Background);--_ui5-v2-5-0_switch_handle_inactive_background_color: var(--sapButton_Handle_Background);--_ui5-v2-5-0_switch_handle_hover_active_background_color: var(--sapButton_Handle_Selected_Hover_Background);--_ui5-v2-5-0_switch_handle_hover_inactive_background_color: var(--sapButton_Handle_Hover_Background);--_ui5-v2-5-0_switch_handle_active_border_color: var(--sapButton_Handle_Selected_BorderColor);--_ui5-v2-5-0_switch_handle_inactive_border_color: var(--sapButton_Handle_BorderColor);--_ui5-v2-5-0_switch_handle_hover_active_border_color: var(--sapButton_Handle_Selected_BorderColor);--_ui5-v2-5-0_switch_handle_hover_inactive_border_color: var(--sapButton_Handle_BorderColor);--_ui5-v2-5-0_switch_handle_semantic_accept_background_color: var(--sapButton_Handle_Positive_Background);--_ui5-v2-5-0_switch_handle_semantic_reject_background_color: var(--sapButton_Handle_Negative_Background);--_ui5-v2-5-0_switch_handle_semantic_hover_accept_background_color: var(--sapButton_Handle_Positive_Hover_Background);--_ui5-v2-5-0_switch_handle_semantic_hover_reject_background_color: var(--sapButton_Handle_Negative_Hover_Background);--_ui5-v2-5-0_switch_handle_semantic_accept_border_color: var(--sapButton_Handle_Positive_BorderColor);--_ui5-v2-5-0_switch_handle_semantic_reject_border_color: var(--sapButton_Handle_Negative_BorderColor);--_ui5-v2-5-0_switch_handle_semantic_hover_accept_border_color: var(--sapButton_Handle_Positive_BorderColor);--_ui5-v2-5-0_switch_handle_semantic_hover_reject_border_color: var(--sapButton_Handle_Negative_BorderColor);--_ui5-v2-5-0_switch_handle_on_hover_box_shadow: 0 0 0 .125rem var(--sapButton_Handle_Selected_Hover_BorderColor);--_ui5-v2-5-0_switch_handle_off_hover_box_shadow: 0 0 0 .125rem var(--sapButton_Handle_Hover_BorderColor);--_ui5-v2-5-0_switch_handle_semantic_on_hover_box_shadow: 0 0 0 .125rem var(--sapButton_Handle_Positive_Hover_BorderColor);--_ui5-v2-5-0_switch_handle_semantic_off_hover_box_shadow: 0 0 0 .125rem var(--sapButton_Handle_Negative_Hover_BorderColor);--_ui5-v2-5-0_switch_handle_left: .0625rem;--_ui5-v2-5-0_switch_text_font_family: var(--sapContent_IconFontFamily);--_ui5-v2-5-0_switch_text_font_size: var(--sapFontLargeSize);--_ui5-v2-5-0_switch_text_width: 1.25rem;--_ui5-v2-5-0_switch_text_with_label_font_family: "72-Condensed-Bold" , "72" , "72full" , Arial, Helvetica, sans-serif;--_ui5-v2-5-0_switch_text_with_label_font_size: var(--sapFontSmallSize);--_ui5-v2-5-0_switch_text_with_label_width: 1.75rem;--_ui5-v2-5-0_switch_text_inactive_left: .1875rem;--_ui5-v2-5-0_switch_text_inactive_left_alternate: .0625rem;--_ui5-v2-5-0_switch_text_inactive_right: auto;--_ui5-v2-5-0_switch_text_inactive_right_alternate: 0;--_ui5-v2-5-0_switch_text_active_left: .1875rem;--_ui5-v2-5-0_switch_text_active_left_alternate: .0625rem;--_ui5-v2-5-0_switch_text_active_right: auto;--_ui5-v2-5-0_switch_text_active_color: var(--sapButton_Handle_Selected_TextColor);--_ui5-v2-5-0_switch_text_inactive_color: var(--sapButton_Handle_TextColor);--_ui5-v2-5-0_switch_text_semantic_accept_color: var(--sapButton_Handle_Positive_TextColor);--_ui5-v2-5-0_switch_text_semantic_reject_color: var(--sapButton_Handle_Negative_TextColor);--_ui5-v2-5-0_switch_text_overflow: hidden;--_ui5-v2-5-0_switch_text_z_index: 1;--_ui5-v2-5-0_switch_text_hidden: hidden;--_ui5-v2-5-0_switch_text_min_width: none;--_ui5-v2-5-0_switch_icon_width: 1rem;--_ui5-v2-5-0_switch_icon_height: 1rem;--_ui5-v2-5-0_select_disabled_background: var(--sapField_Background);--_ui5-v2-5-0_select_disabled_border_color: var(--sapField_BorderColor);--_ui5-v2-5-0_select_state_error_warning_border_style: solid;--_ui5-v2-5-0_select_state_error_warning_border_width: .125rem;--_ui5-v2-5-0_select_focus_width: 1px;--_ui5-v2-5-0_select_label_color: var(--sapField_TextColor);--_ui5-v2-5-0_select_hover_icon_left_border: none;--_ui5-v2-5-0_select_option_focus_border_radius: var(--sapElement_BorderCornerRadius);--_ui5-v2-5-0_split_button_host_transparent_hover_background: transparent;--_ui5-v2-5-0_split_button_transparent_disabled_background: transparent;--_ui5-v2-5-0_split_button_host_default_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_BorderColor);--_ui5-v2-5-0_split_button_host_attention_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_Attention_BorderColor);--_ui5-v2-5-0_split_button_host_emphasized_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_Emphasized_BorderColor);--_ui5-v2-5-0_split_button_host_positive_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_Accept_BorderColor);--_ui5-v2-5-0_split_button_host_negative_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_Reject_BorderColor);--_ui5-v2-5-0_split_button_host_transparent_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_Lite_BorderColor);--_ui5-v2-5-0_split_text_button_border_color: transparent;--_ui5-v2-5-0_split_text_button_background_color: transparent;--_ui5-v2-5-0_split_text_button_emphasized_border: var(--sapButton_BorderWidth) solid var(--sapButton_Emphasized_BorderColor);--_ui5-v2-5-0_split_text_button_emphasized_border_width: .0625rem;--_ui5-v2-5-0_split_text_button_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_text_button_emphasized_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Emphasized_BorderColor);--_ui5-v2-5-0_split_text_button_positive_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Accept_BorderColor);--_ui5-v2-5-0_split_text_button_negative_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Reject_BorderColor);--_ui5-v2-5-0_split_text_button_attention_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Attention_BorderColor);--_ui5-v2-5-0_split_text_button_transparent_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_arrow_button_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_arrow_button_emphasized_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Emphasized_BorderColor);--_ui5-v2-5-0_split_arrow_button_emphasized_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_Emphasized_BorderColor);--_ui5-v2-5-0_split_arrow_button_positive_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Accept_BorderColor);--_ui5-v2-5-0_split_arrow_button_negative_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Reject_BorderColor);--_ui5-v2-5-0_split_arrow_button_attention_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_Attention_BorderColor);--_ui5-v2-5-0_split_arrow_button_transparent_hover_border: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_text_button_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_text_button_emphasized_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_Emphasized_BorderColor);--_ui5-v2-5-0_split_text_button_positive_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_Accept_BorderColor);--_ui5-v2-5-0_split_text_button_negative_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_Reject_BorderColor);--_ui5-v2-5-0_split_text_button_attention_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_Attention_BorderColor);--_ui5-v2-5-0_split_text_button_transparent_hover_border_left: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_button_focused_border: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_split_button_focused_border_radius: .375rem;--_ui5-v2-5-0_split_button_hover_border_radius: var(--_ui5-v2-5-0_button_border_radius);--_ui5-v2-5-0_split_button_middle_separator_width: 0;--_ui5-v2-5-0_split_button_middle_separator_left: -.0625rem;--_ui5-v2-5-0_split_button_middle_separator_hover_display: none;--_ui5-v2-5-0_split_button_text_button_width: 2.375rem;--_ui5-v2-5-0_split_button_text_button_right_border_width: .0625rem;--_ui5-v2-5-0_split_button_transparent_hover_background: var(--sapButton_Lite_Hover_Background);--_ui5-v2-5-0_split_button_transparent_hover_color: var(--sapButton_TextColor);--_ui5-v2-5-0_split_button_host_transparent_hover_box_shadow: inset 0 0 0 var(--sapButton_BorderWidth) var(--sapButton_BorderColor);--_ui5-v2-5-0_split_button_inner_focused_border_radius_outer: .375rem;--_ui5-v2-5-0_split_button_inner_focused_border_radius_inner: .375rem;--_ui5-v2-5-0_split_button_emphasized_separator_color: transparent;--_ui5-v2-5-0_split_button_positive_separator_color: transparent;--_ui5-v2-5-0_split_button_negative_separator_color: transparent;--_ui5-v2-5-0_split_button_attention_separator_color: transparent;--_ui5-v2-5-0_split_button_attention_separator_color_default: var(--sapButton_Attention_TextColor);--_ui5-v2-5-0_split_text_button_hover_border_right: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_text_button_emphasized_hover_border_right: none;--_ui5-v2-5-0_split_text_button_positive_hover_border_right: var(--sapButton_BorderWidth) solid var(--sapButton_Accept_BorderColor);--_ui5-v2-5-0_split_text_button_negative_hover_border_right: var(--sapButton_BorderWidth) solid var(--sapButton_Reject_BorderColor);--_ui5-v2-5-0_split_text_button_attention_hover_border_right: var(--sapButton_BorderWidth) solid var(--sapButton_Attention_BorderColor);--_ui5-v2-5-0_split_text_button_transparent_hover_border_right: var(--sapButton_BorderWidth) solid var(--sapButton_BorderColor);--_ui5-v2-5-0_split_button_middle_separator_hover_display_emphasized: none;--_ui5-v2-5-0_tc_header_height: var(--_ui5-v2-5-0_tc_item_height);--_ui5-v2-5-0_tc_header_height_text_only: var(--_ui5-v2-5-0_tc_item_text_only_height);--_ui5-v2-5-0_tc_header_height_text_with_additional_text: var(--_ui5-v2-5-0_tc_item_text_only_with_additional_text_height);--_ui5-v2-5-0_tc_header_box_shadow: var(--sapContent_HeaderShadow);--_ui5-v2-5-0_tc_header_background: var(--sapObjectHeader_Background);--_ui5-v2-5-0_tc_header_background_translucent: var(--sapObjectHeader_Background);--_ui5-v2-5-0_tc_content_background: var(--sapBackgroundColor);--_ui5-v2-5-0_tc_content_background_translucent: var(--sapGroup_ContentBackground);--_ui5-v2-5-0_tc_headeritem_padding: 1rem;--_ui5-v2-5-0_tc_headerItem_additional_text_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_tc_headerItem_text_selected_color: var(--sapSelectedColor);--_ui5-v2-5-0_tc_headerItem_text_selected_hover_color: var(--sapSelectedColor);--_ui5-v2-5-0_tc_headerItem_additional_text_font_weight: normal;--_ui5-v2-5-0_tc_headerItem_neutral_color: var(--sapNeutralTextColor);--_ui5-v2-5-0_tc_headerItem_positive_color: var(--sapPositiveTextColor);--_ui5-v2-5-0_tc_headerItem_negative_color: var(--sapNegativeTextColor);--_ui5-v2-5-0_tc_headerItem_critical_color: var(--sapCriticalTextColor);--_ui5-v2-5-0_tc_headerItem_neutral_border_color: var(--sapNeutralElementColor);--_ui5-v2-5-0_tc_headerItem_positive_border_color: var(--sapPositiveElementColor);--_ui5-v2-5-0_tc_headerItem_negative_border_color: var(--sapNegativeElementColor);--_ui5-v2-5-0_tc_headerItem_critical_border_color: var(--sapCriticalElementColor);--_ui5-v2-5-0_tc_headerItem_neutral_selected_border_color: var(--_ui5-v2-5-0_tc_headerItem_neutral_color);--_ui5-v2-5-0_tc_headerItem_positive_selected_border_color: var(--_ui5-v2-5-0_tc_headerItem_positive_color);--_ui5-v2-5-0_tc_headerItem_negative_selected_border_color: var(--_ui5-v2-5-0_tc_headerItem_negative_color);--_ui5-v2-5-0_tc_headerItem_critical_selected_border_color: var(--_ui5-v2-5-0_tc_headerItem_critical_color);--_ui5-v2-5-0_tc_headerItem_transition: none;--_ui5-v2-5-0_tc_headerItem_hover_border_visibility: hidden;--_ui5-v2-5-0_tc_headerItemContent_border_radius: .125rem .125rem 0 0;--_ui5-v2-5-0_tc_headerItemContent_border_bg: transparent;--_ui5-v2-5-0_tc_headerItem_neutral_border_bg: transparent;--_ui5-v2-5-0_tc_headerItem_positive_border_bg: transparent;--_ui5-v2-5-0_tc_headerItem_negative_border_bg: transparent;--_ui5-v2-5-0_tc_headerItem_critical_border_bg: transparent;--_ui5-v2-5-0_tc_headerItemContent_border_height: 0;--_ui5-v2-5-0_tc_headerItemContent_focus_offset: 1rem;--_ui5-v2-5-0_tc_headerItem_text_focus_border_offset_left: 0px;--_ui5-v2-5-0_tc_headerItem_text_focus_border_offset_right: 0px;--_ui5-v2-5-0_tc_headerItem_text_focus_border_offset_top: 0px;--_ui5-v2-5-0_tc_headerItem_text_focus_border_offset_bottom: 0px;--_ui5-v2-5-0_tc_headerItem_mixed_mode_focus_border_offset_left: .75rem;--_ui5-v2-5-0_tc_headerItem_mixed_mode_focus_border_offset_right: .625rem;--_ui5-v2-5-0_tc_headerItem_mixed_mode_focus_border_offset_top: .75rem;--_ui5-v2-5-0_tc_headerItem_mixed_mode_focus_border_offset_bottom: .75rem;--_ui5-v2-5-0_tc_headerItemContent_focus_border: none;--_ui5-v2-5-0_tc_headerItemContent_default_focus_border: none;--_ui5-v2-5-0_tc_headerItemContent_focus_border_radius: 0;--_ui5-v2-5-0_tc_headerItemSemanticIcon_display: none;--_ui5-v2-5-0_tc_headerItemSemanticIcon_size: .75rem;--_ui5-v2-5-0_tc_mixedMode_itemText_font_family: var(--sapFontFamily);--_ui5-v2-5-0_tc_mixedMode_itemText_font_size: var(--sapFontSmallSize);--_ui5-v2-5-0_tc_mixedMode_itemText_font_weight: normal;--_ui5-v2-5-0_tc_overflowItem_positive_color: var(--sapPositiveColor);--_ui5-v2-5-0_tc_overflowItem_negative_color: var(--sapNegativeColor);--_ui5-v2-5-0_tc_overflowItem_critical_color: var(--sapCriticalColor);--_ui5-v2-5-0_tc_overflowItem_focus_offset: .125rem;--_ui5-v2-5-0_tc_overflowItem_extraIndent: 0rem;--_ui5-v2-5-0_tc_headerItemIcon_positive_selected_background: var(--sapPositiveColor);--_ui5-v2-5-0_tc_headerItemIcon_negative_selected_background: var(--sapNegativeColor);--_ui5-v2-5-0_tc_headerItemIcon_critical_selected_background: var(--sapCriticalColor);--_ui5-v2-5-0_tc_headerItemIcon_neutral_selected_background: var(--sapNeutralColor);--_ui5-v2-5-0_tc_headerItemIcon_semantic_selected_color: var(--sapGroup_ContentBackground);--_ui5-v2-5-0_tc_header_border_bottom: .0625rem solid var(--sapObjectHeader_Background);--_ui5-v2-5-0_tc_headerItemContent_border_bottom: .1875rem solid var(--sapSelectedColor);--_ui5-v2-5-0_tc_headerItem_color: var(--sapTextColor);--_ui5-v2-5-0_tc_overflowItem_default_color: var(--sapTextColor);--_ui5-v2-5-0_tc_overflowItem_current_color: CurrentColor;--_ui5-v2-5-0_tc_content_border_bottom: .0625rem solid var(--sapObjectHeader_BorderColor);--_ui5-v2-5-0_tc_headerItem_expand_button_margin_inline_start: 0rem;--_ui5-v2-5-0_tc_headerItem_single_click_expand_button_margin_inline_start: .25rem;--_ui5-v2-5-0_tc_headerItem_expand_button_border_radius: .25rem;--_ui5-v2-5-0_tc_headerItem_expand_button_separator_display: inline-block;--_ui5-v2-5-0_tc_headerItem_focus_border: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_tc_headerItem_focus_border_offset: -5px;--_ui5-v2-5-0_tc_headerItemIcon_focus_border_radius: 50%;--_ui5-v2-5-0_tc_headerItem_focus_border_radius: .375rem;--_ui5-v2-5-0_tc_headeritem_text_font_weight: bold;--_ui5-v2-5-0_tc_headerItem_focus_offset: 1px;--_ui5-v2-5-0_tc_headerItem_text_hover_color: var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_tc_headerItemIcon_border: .125rem solid var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_tc_headerItemIcon_color: var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_tc_headerItemIcon_selected_background: var(--sapContent_Selected_ForegroundColor);--_ui5-v2-5-0_tc_headerItemIcon_background_color: var(--sapContent_Selected_Background);--_ui5-v2-5-0_tc_headerItemIcon_selected_color: var(--sapContent_ContrastIconColor);--_ui5-v2-5-0_tc_mixedMode_itemText_color: var(--sapTextColor);--_ui5-v2-5-0_tc_overflow_text_color: var(--sapTextColor);--_ui5-v2-5-0_text_max_lines: initial;--_ui5-v2-5-0_textarea_state_border_width: .125rem;--_ui5-v2-5-0_textarea_information_border_width: .125rem;--_ui5-v2-5-0_textarea_placeholder_font_style: italic;--_ui5-v2-5-0_textarea_value_state_error_warning_placeholder_font_weight: normal;--_ui5-v2-5-0_textarea_error_placeholder_font_style: italic;--_ui5-v2-5-0_textarea_error_placeholder_color: var(--sapField_PlaceholderTextColor);--_ui5-v2-5-0_textarea_error_hover_background_color: var(--sapField_Hover_Background);--_ui5-v2-5-0_textarea_disabled_opacity: .4;--_ui5-v2-5-0_textarea_focus_pseudo_element_content: "";--_ui5-v2-5-0_textarea_min_height: 2.25rem;--_ui5-v2-5-0_textarea_padding_right_and_left_readonly: .5625rem;--_ui5-v2-5-0_textarea_padding_top_readonly: .4375rem;--_ui5-v2-5-0_textarea_exceeded_text_height: 1rem;--_ui5-v2-5-0_textarea_hover_border: none;--_ui5-v2-5-0_textarea_focus_border_radius: .25rem;--_ui5-v2-5-0_textarea_error_warning_border_style: none;--_ui5-v2-5-0_textarea_line_height: 1.5;--_ui5-v2-5-0_textarea_focused_value_state_error_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_textarea_focused_value_state_warning_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_textarea_focused_value_state_success_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_textarea_focused_value_state_information_background: var(--sapField_Hover_Background);--_ui5-v2-5-0_textarea_focused_value_state_error_focus_outline_color: var(--sapField_InvalidColor);--_ui5-v2-5-0_textarea_focused_value_state_warning_focus_outline_color: var(--sapField_WarningColor);--_ui5-v2-5-0_textarea_focused_value_state_success_focus_outline_color: var(--sapField_SuccessColor);--_ui5-v2-5-0_textarea_focus_offset: 0;--_ui5-v2-5-0_textarea_readonly_focus_offset: 1px;--_ui5-v2-5-0_textarea_focus_outline_color: var(--sapField_Active_BorderColor);--_ui5-v2-5-0_textarea_value_state_focus_offset: 1px;--_ui5-v2-5-0_textarea_wrapper_padding: .0625rem;--_ui5-v2-5-0_textarea_success_wrapper_padding: .0625rem;--_ui5-v2-5-0_textarea_warning_error_wrapper_padding: .0625rem .0625rem .125rem .0625rem;--_ui5-v2-5-0_textarea_information_wrapper_padding: .0625rem .0625rem .125rem .0625rem;--_ui5-v2-5-0_textarea_padding_bottom_readonly: .375rem;--_ui5-v2-5-0_textarea_padding_top_error_warning: .5rem;--_ui5-v2-5-0_textarea_padding_bottom_error_warning: .4375rem;--_ui5-v2-5-0_textarea_padding_top_information: .5rem;--_ui5-v2-5-0_textarea_padding_bottom_information: .4375rem;--_ui5-v2-5-0_textarea_padding_right_and_left: .625rem;--_ui5-v2-5-0_textarea_padding_right_and_left_error_warning: .625rem;--_ui5-v2-5-0_textarea_padding_right_and_left_information: .625rem;--_ui5-v2-5-0_textarea_readonly_border_style: dashed;--_ui5-v2-5-0_time_picker_border: .0625rem solid transparent;--_ui5-v2-5-0-time_picker_border_radius: .25rem;--_ui5-v2-5-0_toast_vertical_offset: 3rem;--_ui5-v2-5-0_toast_horizontal_offset: 2rem;--_ui5-v2-5-0_toast_background: var(--sapList_Background);--_ui5-v2-5-0_toast_shadow: var(--sapContent_Shadow2);--_ui5-v2-5-0_toast_offset_width: -.1875rem;--_ui5-v2-5-0_toggle_button_pressed_focussed: var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_toggle_button_pressed_focussed_hovered: var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_toggle_button_selected_positive_text_color: var(--sapButton_Selected_TextColor);--_ui5-v2-5-0_toggle_button_selected_negative_text_color: var(--sapButton_Selected_TextColor);--_ui5-v2-5-0_toggle_button_selected_attention_text_color: var(--sapButton_Selected_TextColor);--_ui5-v2-5-0_toggle_button_emphasized_pressed_focussed_hovered: var(--sapContent_FocusColor);--_ui5-v2-5-0_toggle_button_emphasized_text_shadow: none;--_ui5-v2-5-0_yearpicker_item_margin: .0625rem;--_ui5-v2-5-0_yearpicker_item_border: .0625rem solid var(--sapButton_Lite_BorderColor);--_ui5-v2-5-0_yearpicker_item_hover_border: .0625rem solid var(--sapButton_Lite_Hover_BorderColor);--_ui5-v2-5-0_yearpicker_item_active_border: .0625rem solid var(--sapButton_Lite_Active_BorderColor);--_ui5-v2-5-0_yearpicker_item_selected_border: .0625rem solid var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_yearpicker_item_selected_hover_border: .0625rem solid var(--sapButton_Selected_Hover_BorderColor);--_ui5-v2-5-0_yearpicker_item_border_radius: .5rem;--_ui5-v2-5-0_calendar_header_middle_button_width: 6.25rem;--_ui5-v2-5-0_calendar_header_middle_button_flex: 1 1 auto;--_ui5-v2-5-0_calendar_header_middle_button_focus_after_display: block;--_ui5-v2-5-0_calendar_header_middle_button_focus_after_width: calc(100% - .375rem) ;--_ui5-v2-5-0_calendar_header_middle_button_focus_after_height: calc(100% - .375rem) ;--_ui5-v2-5-0_calendar_header_middle_button_focus_after_top_offset: .125rem;--_ui5-v2-5-0_calendar_header_middle_button_focus_after_left_offset: .125rem;--_ui5-v2-5-0_calendar_header_arrow_button_border: none;--_ui5-v2-5-0_calendar_header_arrow_button_border_radius: .5rem;--_ui5-v2-5-0_calendar_header_button_background_color: var(--sapButton_Lite_Background);--_ui5-v2-5-0_calendar_header_arrow_button_box_shadow: 0 0 .125rem 0 rgb(85 107 130 / 72%);--_ui5-v2-5-0_calendar_header_middle_button_focus_border_radius: .5rem;--_ui5-v2-5-0_calendar_header_middle_button_focus_border: none;--_ui5-v2-5-0_calendar_header_middle_button_focus_after_border: none;--_ui5-v2-5-0_calendar_header_middle_button_focus_background: transparent;--_ui5-v2-5-0_calendar_header_middle_button_focus_outline: .125rem solid var(--sapSelectedColor);--_ui5-v2-5-0_calendar_header_middle_button_focus_active_outline: .0625rem solid var(--sapSelectedColor);--_ui5-v2-5-0_calendar_header_middle_button_focus_active_background: transparent;--_ui5-v2-5-0_token_background: var(--sapButton_TokenBackground);--_ui5-v2-5-0_token_readonly_background: var(--sapButton_TokenBackground);--_ui5-v2-5-0_token_readonly_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_token_right_margin: .3125rem;--_ui5-v2-5-0_token_padding: .25rem 0;--_ui5-v2-5-0_token_left_padding: .3125rem;--_ui5-v2-5-0_token_focused_selected_border: 1px solid var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_token_focus_offset: -.25rem;--_ui5-v2-5-0_token_focus_outline_width: .0625rem;--_ui5-v2-5-0_token_hover_border_color: var(--sapButton_TokenBorderColor);--_ui5-v2-5-0_token_selected_focus_outline: none;--_ui5-v2-5-0_token_focus_outline: none;--_ui5-v2-5-0_token_outline_offset: .125rem;--_ui5-v2-5-0_token_selected_hover_border_color: var(--sapButton_Selected_BorderColor);--ui5-v2-5-0_token_focus_pseudo_element_content: "";--_ui5-v2-5-0_token_border_radius: .375rem;--_ui5-v2-5-0_token_focus_outline_border_radius: .5rem;--_ui5-v2-5-0_token_text_color: var(--sapTextColor);--_ui5-v2-5-0_token_selected_text_font_family: var(--sapFontSemiboldDuplexFamily);--_ui5-v2-5-0_token_selected_internal_border_bottom: .125rem solid var(--sapButton_Selected_BorderColor);--_ui5-v2-5-0_token_selected_internal_border_bottom_radius: .1875rem;--_ui5-v2-5-0_token_text_icon_top: .0625rem;--_ui5-v2-5-0_token_selected_focused_offset_bottom: -.375rem;--_ui5-v2-5-0_token_readonly_padding: .25rem .3125rem;--_ui5-v2-5-0_tokenizer_gap: .625rem .25rem;--_ui5-v2-5-0_tokenizer-popover_offset: .3125rem;--_ui5-v2-5-0_tokenizer_n_more_text_color: var(--sapLinkColor);--_ui5-v2-5-0-multi_combobox_token_margin_top: 1px;--_ui5-v2-5-0_slider_progress_container_dot_background: var(--sapField_BorderColor);--_ui5-v2-5-0_slider_progress_border: none;--_ui5-v2-5-0_slider_padding: 1.406rem 1.0625rem;--_ui5-v2-5-0_slider_inner_height: .25rem;--_ui5-v2-5-0_slider_outer_height: 1.6875rem;--_ui5-v2-5-0_slider_progress_border_radius: .25rem;--_ui5-v2-5-0_slider_tickmark_bg: var(--sapField_BorderColor);--_ui5-v2-5-0_slider_handle_margin_left: calc(-1 * (var(--_ui5-v2-5-0_slider_handle_width) / 2));--_ui5-v2-5-0_slider_handle_outline_offset: .075rem;--_ui5-v2-5-0_slider_progress_outline: .0625rem dotted var(--sapContent_FocusColor);--_ui5-v2-5-0_slider_progress_outline_offset: -.8125rem;--_ui5-v2-5-0_slider_disabled_opacity: .4;--_ui5-v2-5-0_slider_tooltip_border_color: var(--sapField_BorderColor);--_ui5-v2-5-0_range_slider_handle_background_focus: transparent;--_ui5-v2-5-0_slider_progress_box_sizing: content-box;--_ui5-v2-5-0_range_slider_focus_outline_width: 100%;--_ui5-v2-5-0_slider_progress_outline_offset_left: 0;--_ui5-v2-5-0_range_slider_focus_outline_radius: 0;--_ui5-v2-5-0_slider_progress_container_top: 0;--_ui5-v2-5-0_slider_progress_height: 100%;--_ui5-v2-5-0_slider_active_progress_border: none;--_ui5-v2-5-0_slider_active_progress_left: 0;--_ui5-v2-5-0_slider_active_progress_top: 0;--_ui5-v2-5-0_slider_no_tickmarks_progress_container_top: var(--_ui5-v2-5-0_slider_progress_container_top);--_ui5-v2-5-0_slider_no_tickmarks_progress_height: var(--_ui5-v2-5-0_slider_progress_height);--_ui5-v2-5-0_slider_no_tickmarks_active_progress_border: var(--_ui5-v2-5-0_slider_active_progress_border);--_ui5-v2-5-0_slider_no_tickmarks_active_progress_left: var(--_ui5-v2-5-0_slider_active_progress_left);--_ui5-v2-5-0_slider_no_tickmarks_active_progress_top: var(--_ui5-v2-5-0_slider_active_progress_top);--_ui5-v2-5-0_slider_handle_focus_visibility: none;--_ui5-v2-5-0_slider_handle_icon_size: 1rem;--_ui5-v2-5-0_slider_progress_container_background: var(--sapSlider_Background);--_ui5-v2-5-0_slider_progress_container_dot_display: block;--_ui5-v2-5-0_slider_inner_min_width: 4rem;--_ui5-v2-5-0_slider_progress_background: var(--sapSlider_Selected_Background);--_ui5-v2-5-0_slider_progress_before_background: var(--sapSlider_Selected_Background);--_ui5-v2-5-0_slider_progress_after_background: var(--sapContent_MeasureIndicatorColor);--_ui5-v2-5-0_slider_handle_background: var(--sapSlider_HandleBackground);--_ui5-v2-5-0_slider_handle_icon_display: inline-block;--_ui5-v2-5-0_slider_handle_border: .0625rem solid var(--sapSlider_HandleBorderColor);--_ui5-v2-5-0_slider_handle_border_radius: .5rem;--_ui5-v2-5-0_slider_handle_height: 1.5rem;--_ui5-v2-5-0_slider_handle_width: 2rem;--_ui5-v2-5-0_slider_handle_top: -.625rem;--_ui5-v2-5-0_slider_handle_font_family: "SAP-icons";--_ui5-v2-5-0_slider_handle_hover_border: .0625rem solid var(--sapSlider_Hover_HandleBorderColor);--_ui5-v2-5-0_slider_handle_focus_border: .125rem solid var(--sapContent_FocusColor);--_ui5-v2-5-0_slider_handle_background_focus: var(--sapSlider_Active_RangeHandleBackground);--_ui5-v2-5-0_slider_handle_outline: none;--_ui5-v2-5-0_slider_handle_hover_background: var(--sapSlider_Hover_HandleBackground);--_ui5-v2-5-0_slider_tooltip_background: var(--sapField_Focus_Background);--_ui5-v2-5-0_slider_tooltip_border: none;--_ui5-v2-5-0_slider_tooltip_border_radius: .5rem;--_ui5-v2-5-0_slider_tooltip_box_shadow: var(--sapContent_Shadow1);--_ui5-v2-5-0_range_slider_legacy_progress_focus_display: none;--_ui5-v2-5-0_range_slider_progress_focus_display: block;--_ui5-v2-5-0_slider_tickmark_in_range_bg: var(--sapSlider_Selected_BorderColor);--_ui5-v2-5-0_slider_label_fontsize: var(--sapFontSmallSize);--_ui5-v2-5-0_slider_label_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_slider_tooltip_min_width: 2rem;--_ui5-v2-5-0_slider_tooltip_padding: .25rem;--_ui5-v2-5-0_slider_tooltip_fontsize: var(--sapFontSmallSize);--_ui5-v2-5-0_slider_tooltip_color: var(--sapContent_LabelColor);--_ui5-v2-5-0_slider_tooltip_height: 1.375rem;--_ui5-v2-5-0_slider_handle_focus_width: 1px;--_ui5-v2-5-0_slider_start_end_point_size: .5rem;--_ui5-v2-5-0_slider_start_end_point_left: -.75rem;--_ui5-v2-5-0_slider_start_end_point_top: -.125rem;--_ui5-v2-5-0_slider_handle_focused_tooltip_distance: calc(var(--_ui5-v2-5-0_slider_tooltip_bottom) - var(--_ui5-v2-5-0_slider_handle_focus_width));--_ui5-v2-5-0_slider_tooltip_border_box: border-box;--_ui5-v2-5-0_range_slider_handle_active_background: var(--sapSlider_Active_RangeHandleBackground);--_ui5-v2-5-0_range_slider_active_handle_icon_display: none;--_ui5-v2-5-0_range_slider_progress_focus_top: -15px;--_ui5-v2-5-0_range_slider_progress_focus_left: calc(-1 * (var(--_ui5-v2-5-0_slider_handle_width) / 2) - 5px);--_ui5-v2-5-0_range_slider_progress_focus_padding: 0 1rem 0 1rem;--_ui5-v2-5-0_range_slider_progress_focus_width: calc(100% + var(--_ui5-v2-5-0_slider_handle_width) + 10px);--_ui5-v2-5-0_range_slider_progress_focus_height: calc(var(--_ui5-v2-5-0_slider_handle_height) + 10px);--_ui5-v2-5-0_range_slider_root_hover_handle_icon_display: inline-block;--_ui5-v2-5-0_range_slider_root_hover_handle_bg: var(--_ui5-v2-5-0_slider_handle_hover_background);--_ui5-v2-5-0_range_slider_root_active_handle_icon_display: none;--_ui5-v2-5-0_slider_tickmark_height: .5rem;--_ui5-v2-5-0_slider_tickmark_top: -2px;--_ui5-v2-5-0_slider_handle_box_sizing: border-box;--_ui5-v2-5-0_range_slider_handle_background: var(--sapSlider_RangeHandleBackground);--_ui5-v2-5-0_slider_tooltip_bottom: 2rem;--_ui5-v2-5-0_value_state_message_border: none;--_ui5-v2-5-0_value_state_header_border: none;--_ui5-v2-5-0_input_value_state_icon_offset: .5rem;--_ui5-v2-5-0_value_state_header_box_shadow_error: inset 0 -.0625rem var(--sapField_InvalidColor);--_ui5-v2-5-0_value_state_header_box_shadow_information: inset 0 -.0625rem var(--sapField_InformationColor);--_ui5-v2-5-0_value_state_header_box_shadow_success: inset 0 -.0625rem var(--sapField_SuccessColor);--_ui5-v2-5-0_value_state_header_box_shadow_warning: inset 0 -.0625rem var(--sapField_WarningColor);--_ui5-v2-5-0_value_state_message_icon_offset_phone: 1rem;--_ui5-v2-5-0_value_state_header_border_bottom: none;--_ui5-v2-5-0_input_value_state_icon_display: inline-block;--_ui5-v2-5-0_value_state_message_padding: .5rem .5rem .5rem 1.875rem;--_ui5-v2-5-0_value_state_header_padding: .5rem .5rem .5rem 1.875rem;--_ui5-v2-5-0_value_state_message_popover_box_shadow: var(--sapContent_Shadow1);--_ui5-v2-5-0_value_state_message_icon_width: 1rem;--_ui5-v2-5-0_value_state_message_icon_height: 1rem;--_ui5-v2-5-0_value_state_header_offset: -.25rem;--_ui5-v2-5-0_value_state_message_popover_border_radius: var(--sapPopover_BorderCornerRadius);--_ui5-v2-5-0_value_state_message_padding_phone: .5rem .5rem .5rem 2.375rem;--_ui5-v2-5-0_value_state_message_line_height: 1.125rem;--_ui5-v2-5-0-toolbar-padding-left: .5rem;--_ui5-v2-5-0-toolbar-padding-right: .5rem;--_ui5-v2-5-0-toolbar-item-margin-left: 0;--_ui5-v2-5-0-toolbar-item-margin-right: .25rem;--_ui5-v2-5-0_step_input_min_width: 7.25rem;--_ui5-v2-5-0_step_input_padding: 2.5rem;--_ui5-v2-5-0_step_input_input_error_background_color: inherit;--_ui5-v2-5-0-step_input_button_state_hover_background_color: var(--sapField_Hover_Background);--_ui5-v2-5-0_step_input_border_style: none;--_ui5-v2-5-0_step_input_border_style_hover: none;--_ui5-v2-5-0_step_input_button_background_color: transparent;--_ui5-v2-5-0_step_input_input_border: none;--_ui5-v2-5-0_step_input_input_margin_top: 0;--_ui5-v2-5-0_step_input_button_display: inline-flex;--_ui5-v2-5-0_step_input_button_left: 0;--_ui5-v2-5-0_step_input_button_right: 0;--_ui5-v2-5-0_step_input_input_border_focused_after: .125rem solid #0070f2;--_ui5-v2-5-0_step_input_input_border_top_bottom_focused_after: 0;--_ui5-v2-5-0_step_input_input_border_radius_focused_after: .25rem;--_ui5-v2-5-0_step_input_input_information_border_color_focused_after: var(--sapField_InformationColor);--_ui5-v2-5-0_step_input_input_warning_border_color_focused_after: var(--sapField_WarningColor);--_ui5-v2-5-0_step_input_input_success_border_color_focused_after: var(--sapField_SuccessColor);--_ui5-v2-5-0_step_input_input_error_border_color_focused_after: var(--sapField_InvalidColor);--_ui5-v2-5-0_step_input_disabled_button_background: none;--_ui5-v2-5-0_step_input_border_color_hover: none;--_ui5-v2-5-0_step_input_border_hover: none;--_ui5-v2-5-0_input_input_background_color: transparent;--_ui5-v2-5-0_load_more_padding: 0;--_ui5-v2-5-0_load_more_border: 1px top solid transparent;--_ui5-v2-5-0_load_more_border_radius: none;--_ui5-v2-5-0_load_more_outline_width: var(--sapContent_FocusWidth);--_ui5-v2-5-0_load_more_border-bottom: var(--sapList_BorderWidth) solid var(--sapList_BorderColor);--_ui5-v2-5-0_calendar_height: 24.5rem;--_ui5-v2-5-0_calendar_width: 20rem;--_ui5-v2-5-0_calendar_padding: 1rem;--_ui5-v2-5-0_calendar_left_right_padding: .5rem;--_ui5-v2-5-0_calendar_top_bottom_padding: 1rem;--_ui5-v2-5-0_calendar_header_height: 3rem;--_ui5-v2-5-0_calendar_header_arrow_button_width: 2.5rem;--_ui5-v2-5-0_calendar_header_padding: .25rem 0;--_ui5-v2-5-0_checkbox_root_side_padding: .6875rem;--_ui5-v2-5-0_checkbox_icon_size: 1rem;--_ui5-v2-5-0_checkbox_partially_icon_size: .75rem;--_ui5-v2-5-0_custom_list_item_rb_min_width: 2.75rem;--_ui5-v2-5-0_day_picker_item_width: 2.25rem;--_ui5-v2-5-0_day_picker_item_height: 2.875rem;--_ui5-v2-5-0_day_picker_empty_height: 3rem;--_ui5-v2-5-0_day_picker_item_justify_content: space-between;--_ui5-v2-5-0_dp_two_calendar_item_now_text_padding_top: .375rem;--_ui5-v2-5-0_daypicker_item_now_selected_two_calendar_focus_special_day_top: 2rem;--_ui5-v2-5-0_daypicker_item_now_selected_two_calendar_focus_special_day_right: 1.4375rem;--_ui5-v2-5-0_dp_two_calendar_item_primary_text_height: 1.8125rem;--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_height: 1rem;--_ui5-v2-5-0_dp_two_calendar_item_text_padding_top: .4375rem;--_ui5-v2-5-0_daypicker_item_now_selected_two_calendar_focus_secondary_text_padding_block: 0 .5rem;--_ui5-v2-5-0-calendar-legend-item-root-focus-offset: -.125rem;--_ui5-v2-5-0-calendar-legend-item-box-margin: .25rem;--_ui5-v2-5-0-calendar-legend-item-box-inner-margin: .5rem;--_ui5-v2-5-0_color-palette-swatch-container-padding: .3125rem .6875rem;--_ui5-v2-5-0_datetime_picker_width: 40.0625rem;--_ui5-v2-5-0_datetime_picker_height: 25rem;--_ui5-v2-5-0_datetime_timeview_width: 17rem;--_ui5-v2-5-0_datetime_timeview_phonemode_width: 19.5rem;--_ui5-v2-5-0_datetime_timeview_padding: 1rem;--_ui5-v2-5-0_datetime_timeview_phonemode_clocks_width: 24.5rem;--_ui5-v2-5-0_datetime_dateview_phonemode_margin_bottom: 0;--_ui5-v2-5-0_dialog_content_min_height: 2.75rem;--_ui5-v2-5-0_dialog_footer_height: 2.75rem;--_ui5-v2-5-0_input_inner_padding: 0 .625rem;--_ui5-v2-5-0_input_inner_padding_with_icon: 0 .25rem 0 .625rem;--_ui5-v2-5-0_input_inner_space_to_tokenizer: .125rem;--_ui5-v2-5-0_input_inner_space_to_n_more_text: .1875rem;--_ui5-v2-5-0_list_no_data_height: 3rem;--_ui5-v2-5-0_list_item_cb_margin_right: 0;--_ui5-v2-5-0_list_item_title_size: var(--sapFontLargeSize);--_ui5-v2-5-0_list_no_data_font_size: var(--sapFontLargeSize);--_ui5-v2-5-0_list_item_img_size: 3rem;--_ui5-v2-5-0_list_item_img_top_margin: .5rem;--_ui5-v2-5-0_list_item_img_bottom_margin: .5rem;--_ui5-v2-5-0_list_item_img_hn_margin: .75rem;--_ui5-v2-5-0_list_item_dropdown_base_height: 2.5rem;--_ui5-v2-5-0_list_item_base_height: var(--sapElement_LineHeight);--_ui5-v2-5-0_list_item_base_padding: 0 1rem;--_ui5-v2-5-0_list_item_icon_size: 1.125rem;--_ui5-v2-5-0_list_item_icon_padding-inline-end: .5rem;--_ui5-v2-5-0_list_item_selection_btn_margin_top: calc(-1 * var(--_ui5-v2-5-0_checkbox_wrapper_padding));--_ui5-v2-5-0_list_item_content_vertical_offset: calc((var(--_ui5-v2-5-0_list_item_base_height) - var(--_ui5-v2-5-0_list_item_title_size)) / 2);--_ui5-v2-5-0_group_header_list_item_height: 2.75rem;--_ui5-v2-5-0_list_busy_row_height: 3rem;--_ui5-v2-5-0_month_picker_item_height: 3rem;--_ui5-v2-5-0_list_buttons_left_space: .125rem;--_ui5-v2-5-0_form_item_min_height: 2.813rem;--_ui5-v2-5-0_form_item_padding: .65rem;--_ui5-v2-5-0-form-group-heading-height: 2.75rem;--_ui5-v2-5-0_popup_default_header_height: 2.75rem;--_ui5-v2-5-0_year_picker_item_height: 3rem;--_ui5-v2-5-0_tokenizer_padding: .25rem;--_ui5-v2-5-0_token_height: 1.625rem;--_ui5-v2-5-0_token_icon_size: .75rem;--_ui5-v2-5-0_token_icon_padding: .25rem .5rem;--_ui5-v2-5-0_token_wrapper_right_padding: .3125rem;--_ui5-v2-5-0_token_wrapper_left_padding: 0;--_ui5-v2-5-0_tl_bubble_padding: 1rem;--_ui5-v2-5-0_tl_indicator_before_bottom: -1.625rem;--_ui5-v2-5-0_tl_padding: 1rem 1rem 1rem .5rem;--_ui5-v2-5-0_tl_li_margin_bottom: 1.625rem;--_ui5-v2-5-0_switch_focus_width_size_horizon_exp: calc(100% + 4px) ;--_ui5-v2-5-0_switch_focus_height_size_horizon_exp: calc(100% + 4px) ;--_ui5-v2-5-0_tc_item_text: 3rem;--_ui5-v2-5-0_tc_item_height: 4.75rem;--_ui5-v2-5-0_tc_item_text_only_height: 2.75rem;--_ui5-v2-5-0_tc_item_text_only_with_additional_text_height: 3.75rem;--_ui5-v2-5-0_tc_item_text_line_height: 1.325rem;--_ui5-v2-5-0_tc_item_icon_circle_size: 2.75rem;--_ui5-v2-5-0_tc_item_icon_size: 1.25rem;--_ui5-v2-5-0_tc_item_add_text_margin_top: .375rem;--_ui5-v2-5-0_textarea_margin: .25rem 0;--_ui5-v2-5-0_radio_button_height: 2.75rem;--_ui5-v2-5-0_radio_button_label_side_padding: .875rem;--_ui5-v2-5-0_radio_button_inner_size: 2.75rem;--_ui5-v2-5-0_radio_button_svg_size: 1.375rem;--_ui5-v2-5-0-responsive_popover_header_height: 2.75rem;--ui5-v2-5-0_side_navigation_item_height: 2.75rem;--_ui5-v2-5-0-tree-indent-step: 1.5rem;--_ui5-v2-5-0-tree-toggle-box-width: 2.75rem;--_ui5-v2-5-0-tree-toggle-box-height: 2.25rem;--_ui5-v2-5-0-tree-toggle-icon-size: 1.0625rem;--_ui5-v2-5-0_timeline_tli_indicator_before_bottom: -1.5rem;--_ui5-v2-5-0_timeline_tli_indicator_before_right: -1.625rem;--_ui5-v2-5-0_timeline_tli_indicator_before_without_icon_bottom: -1.875rem;--_ui5-v2-5-0_timeline_tli_indicator_before_without_icon_right: -1.9375rem;--_ui5-v2-5-0_timeline_tli_indicator_after_top: calc(-100% - 1rem) ;--_ui5-v2-5-0_timeline_tli_indicator_after_height: calc(100% + 1rem) ;--_ui5-v2-5-0_timeline_tli_indicator_before_height: 100%;--_ui5-v2-5-0_timeline_tli_horizontal_indicator_after_width: calc(100% + .25rem) ;--_ui5-v2-5-0_timeline_tli_horizontal_indicator_after_left: 1.9375rem;--_ui5-v2-5-0_timeline_tli_horizontal_without_icon_indicator_before_width: calc(100% + .5rem) ;--_ui5-v2-5-0_timeline_tli_horizontal_indicator_before_width: calc(100% + .5rem) ;--_ui5-v2-5-0_timeline_tli_icon_horizontal_indicator_after_width: calc(100% + .25rem) ;--_ui5-v2-5-0_timeline_tli_without_icon_horizontal_indicator_before_width: calc(100% + .375rem) ;--_ui5-v2-5-0_timeline_tli_horizontal_indicator_short_after_width: 100%;--_ui5-v2-5-0_timeline_tli_last_child_vertical_indicator_before_height: calc(100% - 1.5rem) ;--_ui5-v2-5-0-toolbar-separator-height: 2rem;--_ui5-v2-5-0-toolbar-height: 2.75rem;--_ui5-v2-5-0_toolbar_overflow_padding: .25rem .5rem;--_ui5-v2-5-0_table_cell_padding: .25rem .5rem;--_ui5-v2-5-0_dynamic_page_title_actions_separator_height: var(--_ui5-v2-5-0-toolbar-separator-height);--_ui5-v2-5-0_split_button_middle_separator_top: .625rem;--_ui5-v2-5-0_split_button_middle_separator_height: 1rem;--_ui5-v2-5-0-calendar-legend-item-root-focus-border-radius: .25rem;--_ui5-v2-5-0_color-palette-item-height: 1.75rem;--_ui5-v2-5-0_color-palette-item-hover-height: 2.25rem;--_ui5-v2-5-0_color-palette-item-margin: calc(((var(--_ui5-v2-5-0_color-palette-item-hover-height) - var(--_ui5-v2-5-0_color-palette-item-height)) / 2) + .0625rem);--_ui5-v2-5-0_color-palette-row-width: 12rem;--_ui5-v2-5-0_textarea_padding_top: .5rem;--_ui5-v2-5-0_textarea_padding_bottom: .4375rem;--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_padding_block: 0 .5rem;--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_padding: 0 .5rem;--_ui5-v2-5-0_daypicker_two_calendar_item_selected_focus_margin_bottom: 0;--_ui5-v2-5-0_daypicker_two_calendar_item_selected_focus_padding_right: .5rem}[dir=rtl]{--_ui5-v2-5-0_table_shadow_border_left: inset calc(-1 * var(--sapContent_FocusWidth)) 0 var(--sapContent_FocusColor);--_ui5-v2-5-0_table_shadow_border_right: inset var(--sapContent_FocusWidth) 0 var(--sapContent_FocusColor);--_ui5-v2-5-0_segmented_btn_item_border_left: .0625rem;--_ui5-v2-5-0_segmented_btn_item_border_right: .0625rem;--_ui5-v2-5-0_progress_indicator_bar_border_radius: .5rem;--_ui5-v2-5-0_progress_indicator_remaining_bar_border_radius: .25rem}[data-ui5-compact-size],.ui5-content-density-compact,.sapUiSizeCompact{--_ui5-v2-5-0_input_min_width: 2rem;--_ui5-v2-5-0_input_icon_width: 2rem;--_ui5-v2-5-0_input_information_icon_padding: .3125rem .5rem .1875rem .5rem;--_ui5-v2-5-0_input_information_focused_icon_padding: .3125rem .5rem .25rem .5rem;--_ui5-v2-5-0_input_error_warning_icon_padding: .3125rem .5rem .1875rem .5rem;--_ui5-v2-5-0_input_error_warning_focused_icon_padding: .3125rem .5rem .25rem .5rem;--_ui5-v2-5-0_input_custom_icon_padding: .3125rem .5rem .25rem .5rem;--_ui5-v2-5-0_input_error_warning_custom_icon_padding: .3125rem .5rem .1875rem .5rem;--_ui5-v2-5-0_input_error_warning_custom_focused_icon_padding: .3125rem .5rem .25rem .5rem;--_ui5-v2-5-0_input_information_custom_icon_padding: .3125rem .5rem .1875rem .5rem;--_ui5-v2-5-0_input_information_custom_focused_icon_padding: .3125rem .5rem .25rem .5rem;--_ui5-v2-5-0_input_icon_padding: .3125rem .5rem .25rem .5rem;--_ui5-v2-5-0_panel_header_button_wrapper_padding: .1875rem .25rem;--_ui5-v2-5-0_rating_indicator_item_height: 1em;--_ui5-v2-5-0_rating_indicator_item_width: 1em;--_ui5-v2-5-0_rating_indicator_readonly_item_height: .75em;--_ui5-v2-5-0_rating_indicator_readonly_item_width: .75em;--_ui5-v2-5-0_rating_indicator_component_spacing: .5rem 0px;--_ui5-v2-5-0_radio_button_min_width: 2rem;--_ui5-v2-5-0_radio_button_outer_ring_padding_with_label: 0 .5rem;--_ui5-v2-5-0_radio_button_outer_ring_padding: 0 .5rem;--_ui5-v2-5-0_radio_button_focus_dist: .1875rem;--_ui5-v2-5-0_switch_height: 2rem;--_ui5-v2-5-0_switch_width: 3rem;--_ui5-v2-5-0_switch_min_width: none;--_ui5-v2-5-0_switch_with_label_width: 3.75rem;--_ui5-v2-5-0_switch_root_outline_top: .25rem;--_ui5-v2-5-0_switch_root_outline_bottom: .25rem;--_ui5-v2-5-0_switch_transform: translateX(100%) translateX(-1.375rem);--_ui5-v2-5-0_switch_transform_with_label: translateX(100%) translateX(-1.875rem);--_ui5-v2-5-0_switch_rtl_transform: translateX(1.375rem) translateX(-100%);--_ui5-v2-5-0_switch_rtl_transform_with_label: translateX(1.875rem) translateX(-100%);--_ui5-v2-5-0_switch_track_width: 2rem;--_ui5-v2-5-0_switch_track_height: 1.25rem;--_ui5-v2-5-0_switch_track_with_label_width: 2.75rem;--_ui5-v2-5-0_switch_track_with_label_height: 1.25rem;--_ui5-v2-5-0_switch_handle_width: 1.25rem;--_ui5-v2-5-0_switch_handle_height: 1rem;--_ui5-v2-5-0_switch_handle_with_label_width: 1.75rem;--_ui5-v2-5-0_switch_handle_with_label_height: 1rem;--_ui5-v2-5-0_switch_text_font_size: var(--sapFontSize);--_ui5-v2-5-0_switch_text_width: 1rem;--_ui5-v2-5-0_switch_text_active_left: .1875rem;--_ui5-v2-5-0_textarea_padding_right_and_left_readonly: .4375rem;--_ui5-v2-5-0_textarea_padding_top_readonly: .125rem;--_ui5-v2-5-0_textarea_exceeded_text_height: .375rem;--_ui5-v2-5-0_textarea_min_height: 1.625rem;--_ui5-v2-5-0_textarea_padding_bottom_readonly: .0625rem;--_ui5-v2-5-0_textarea_padding_top_error_warning: .1875rem;--_ui5-v2-5-0_textarea_padding_bottom_error_warning: .125rem;--_ui5-v2-5-0_textarea_padding_top_information: .1875rem;--_ui5-v2-5-0_textarea_padding_bottom_information: .125rem;--_ui5-v2-5-0_textarea_padding_right_and_left: .5rem;--_ui5-v2-5-0_textarea_padding_right_and_left_error_warning: .5rem;--_ui5-v2-5-0_textarea_padding_right_and_left_information: .5rem;--_ui5-v2-5-0_token_selected_focused_offset_bottom: -.25rem;--_ui5-v2-5-0_tokenizer_gap: .375em .25rem;--_ui5-v2-5-0_tokenizer-popover_offset: .1875rem;--_ui5-v2-5-0_slider_handle_icon_size: .875rem;--_ui5-v2-5-0_slider_padding: 1rem 1.0625rem;--_ui5-v2-5-0_range_slider_progress_focus_width: calc(100% + var(--_ui5-v2-5-0_slider_handle_width) + 10px);--_ui5-v2-5-0_range_slider_progress_focus_height: calc(var(--_ui5-v2-5-0_slider_handle_height) + 10px);--_ui5-v2-5-0_range_slider_progress_focus_top: -.8125rem;--_ui5-v2-5-0_slider_tooltip_bottom: 1.75rem;--_ui5-v2-5-0_slider_handle_focused_tooltip_distance: calc(var(--_ui5-v2-5-0_slider_tooltip_bottom) - var(--_ui5-v2-5-0_slider_handle_focus_width));--_ui5-v2-5-0_range_slider_progress_focus_left: calc(-1 * (var(--_ui5-v2-5-0_slider_handle_width) / 2) - 5px);--_ui5-v2-5-0_bar_base_height: 2.5rem;--_ui5-v2-5-0_bar_subheader_height: 2.25rem;--_ui5-v2-5-0_button_base_height: var(--sapElement_Compact_Height);--_ui5-v2-5-0_button_base_padding: .4375rem;--_ui5-v2-5-0_button_base_min_width: 2rem;--_ui5-v2-5-0_button_icon_font_size: 1rem;--_ui5-v2-5-0_calendar_height: 18rem;--_ui5-v2-5-0_calendar_width: 17.75rem;--_ui5-v2-5-0_calendar_left_right_padding: .25rem;--_ui5-v2-5-0_calendar_top_bottom_padding: .5rem;--_ui5-v2-5-0_calendar_header_height: 2rem;--_ui5-v2-5-0_calendar_header_arrow_button_width: 2rem;--_ui5-v2-5-0_calendar_header_padding: 0;--_ui5-v2-5-0-calendar-legend-root-padding: .5rem;--_ui5-v2-5-0-calendar-legend-root-width: 16.75rem;--_ui5-v2-5-0-calendar-legend-item-root-focus-margin: -.125rem;--_ui5-v2-5-0_checkbox_root_side_padding: var(--_ui5-v2-5-0_checkbox_wrapped_focus_padding);--_ui5-v2-5-0_checkbox_width_height: var(--_ui5-v2-5-0_checkbox_compact_width_height);--_ui5-v2-5-0_checkbox_wrapper_padding: var(--_ui5-v2-5-0_checkbox_compact_wrapper_padding);--_ui5-v2-5-0_checkbox_inner_width_height: var(--_ui5-v2-5-0_checkbox_compact_inner_size);--_ui5-v2-5-0_checkbox_icon_size: .75rem;--_ui5-v2-5-0_checkbox_partially_icon_size: .5rem;--_ui5-v2-5-0_custom_list_item_rb_min_width: 2rem;--_ui5-v2-5-0_daypicker_weeknumbers_container_padding_top: 2rem;--_ui5-v2-5-0_day_picker_item_width: 2rem;--_ui5-v2-5-0_day_picker_item_height: 2rem;--_ui5-v2-5-0_day_picker_empty_height: 2.125rem;--_ui5-v2-5-0_day_picker_item_justify_content: flex-end;--_ui5-v2-5-0_dp_two_calendar_item_now_text_padding_top: .5rem;--_ui5-v2-5-0_dp_two_calendar_item_primary_text_height: 1rem;--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_height: .75rem;--_ui5-v2-5-0_dp_two_calendar_item_text_padding_top: .5rem;--_ui5-v2-5-0_daypicker_special_day_top: 1.625rem;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_top: 1.25rem;--_ui5-v2-5-0_daypicker_twocalendar_item_special_day_right: 1.25rem;--_ui5-v2-5-0_daypicker_two_calendar_item_margin_bottom: 0;--_ui5-v2-5-0_daypicker_item_now_selected_two_calendar_focus_special_day_top: 1.125rem;--_ui5-v2-5-0_daypicker_item_now_selected_two_calendar_focus_special_day_right: 1.125rem;--_ui5-v2-5-0_daypicker_item_now_selected_two_calendar_focus_secondary_text_padding_block: 0 1rem;--_ui5-v2-5-0_datetime_picker_height: 20.5rem;--_ui5-v2-5-0_datetime_picker_width: 35.5rem;--_ui5-v2-5-0_datetime_timeview_width: 17rem;--_ui5-v2-5-0_datetime_timeview_phonemode_width: 18.5rem;--_ui5-v2-5-0_datetime_timeview_padding: .5rem;--_ui5-v2-5-0_datetime_timeview_phonemode_clocks_width: 21.125rem;--_ui5-v2-5-0_datetime_dateview_phonemode_margin_bottom: 3.125rem;--_ui5-v2-5-0_dialog_content_min_height: 2.5rem;--_ui5-v2-5-0_dialog_footer_height: 2.5rem;--_ui5-v2-5-0_form_item_min_height: 2rem;--_ui5-v2-5-0_form_item_padding: .25rem;--_ui5-v2-5-0-form-group-heading-height: 2rem;--_ui5-v2-5-0_input_height: var(--sapElement_Compact_Height);--_ui5-v2-5-0_input_inner_padding: 0 .5rem;--_ui5-v2-5-0_input_inner_padding_with_icon: 0 .2rem 0 .5rem;--_ui5-v2-5-0_input_inner_space_to_tokenizer: .125rem;--_ui5-v2-5-0_input_inner_space_to_n_more_text: .125rem;--_ui5-v2-5-0_input_icon_min_width: var(--_ui5-v2-5-0_input_compact_min_width);--_ui5-v2-5-0_menu_item_padding: 0 .75rem 0 .5rem;--_ui5-v2-5-0_menu_item_submenu_icon_right: .75rem;--_ui5-v2-5-0_popup_default_header_height: 2.5rem;--_ui5-v2-5-0_textarea_margin: .1875rem 0;--_ui5-v2-5-0_list_no_data_height: 2rem;--_ui5-v2-5-0_list_item_cb_margin_right: .5rem;--_ui5-v2-5-0_list_item_title_size: var(--sapFontSize);--_ui5-v2-5-0_list_item_img_top_margin: .55rem;--_ui5-v2-5-0_list_no_data_font_size: var(--sapFontSize);--_ui5-v2-5-0_list_item_dropdown_base_height: 2rem;--_ui5-v2-5-0_list_item_base_height: 2rem;--_ui5-v2-5-0_list_item_base_padding: 0 1rem;--_ui5-v2-5-0_list_item_icon_size: 1rem;--_ui5-v2-5-0_list_item_selection_btn_margin_top: calc(-1 * var(--_ui5-v2-5-0_checkbox_wrapper_padding));--_ui5-v2-5-0_list_item_content_vertical_offset: calc((var(--_ui5-v2-5-0_list_item_base_height) - var(--_ui5-v2-5-0_list_item_title_size)) / 2);--_ui5-v2-5-0_list_busy_row_height: 2rem;--_ui5-v2-5-0_list_buttons_left_space: .125rem;--_ui5-v2-5-0_month_picker_item_height: 2rem;--_ui5-v2-5-0_year_picker_item_height: 2rem;--_ui5-v2-5-0_panel_header_height: 2rem;--_ui5-v2-5-0_panel_button_root_height: 2rem;--_ui5-v2-5-0_panel_button_root_width: 2.5rem;--_ui5-v2-5-0_token_height: 1.25rem;--_ui5-v2-5-0_token_right_margin: .25rem;--_ui5-v2-5-0_token_left_padding: .25rem;--_ui5-v2-5-0_token_readonly_padding: .125rem .25rem;--_ui5-v2-5-0_token_focus_offset: -.125rem;--_ui5-v2-5-0_token_icon_size: .75rem;--_ui5-v2-5-0_token_icon_padding: .375rem .375rem;--_ui5-v2-5-0_token_wrapper_right_padding: .25rem;--_ui5-v2-5-0_token_wrapper_left_padding: 0;--_ui5-v2-5-0_token_outline_offset: -.125rem;--_ui5-v2-5-0_tl_bubble_padding: .5rem;--_ui5-v2-5-0_tl_indicator_before_bottom: -.5rem;--_ui5-v2-5-0_tl_padding: .5rem;--_ui5-v2-5-0_tl_li_margin_bottom: .5rem;--_ui5-v2-5-0_tc_item_text: 2rem;--_ui5-v2-5-0_tc_item_text_line_height: 1.325rem;--_ui5-v2-5-0_tc_item_add_text_margin_top: .3125rem;--_ui5-v2-5-0_tc_item_height: 4rem;--_ui5-v2-5-0_tc_header_height: var(--_ui5-v2-5-0_tc_item_height);--_ui5-v2-5-0_tc_item_icon_circle_size: 2rem;--_ui5-v2-5-0_tc_item_icon_size: 1rem;--_ui5-v2-5-0_radio_button_height: 2rem;--_ui5-v2-5-0_radio_button_label_side_padding: .5rem;--_ui5-v2-5-0_radio_button_inner_size: 2rem;--_ui5-v2-5-0_radio_button_svg_size: 1rem;--_ui5-v2-5-0-responsive_popover_header_height: 2.5rem;--ui5-v2-5-0_side_navigation_item_height: 2rem;--_ui5-v2-5-0_slider_handle_height: 1.25rem;--_ui5-v2-5-0_slider_handle_width: 1.5rem;--_ui5-v2-5-0_slider_tooltip_padding: .25rem;--_ui5-v2-5-0_slider_progress_outline_offset: -.625rem;--_ui5-v2-5-0_slider_outer_height: 1.3125rem;--_ui5-v2-5-0_step_input_min_width: 6rem;--_ui5-v2-5-0_step_input_padding: 2rem;--_ui5-v2-5-0-tree-indent-step: .5rem;--_ui5-v2-5-0-tree-toggle-box-width: 2rem;--_ui5-v2-5-0-tree-toggle-box-height: 1.5rem;--_ui5-v2-5-0-tree-toggle-icon-size: .8125rem;--_ui5-v2-5-0_timeline_tli_indicator_before_bottom: -.75rem;--_ui5-v2-5-0_timeline_tli_indicator_before_right: -.5rem;--_ui5-v2-5-0_timeline_tli_indicator_before_without_icon_bottom: -1rem;--_ui5-v2-5-0_timeline_tli_indicator_before_without_icon_right: -.8125rem;--_ui5-v2-5-0_timeline_tli_indicator_before_height: calc(100% - 1.25rem) ;--_ui5-v2-5-0_timeline_tli_horizontal_without_icon_indicator_before_width: var(--_ui5-v2-5-0_timeline_tli_indicator_after_height);--_ui5-v2-5-0_timeline_tli_horizontal_indicator_after_width: var(--_ui5-v2-5-0_timeline_tli_indicator_after_height);--_ui5-v2-5-0_timeline_tli_horizontal_indicator_before_width: var(--_ui5-v2-5-0_timeline_tli_indicator_after_height);--_ui5-v2-5-0_timeline_tli_icon_horizontal_indicator_after_width: var(--_ui5-v2-5-0_timeline_tli_indicator_after_height);--_ui5-v2-5-0_timeline_tli_indicator_after_top: calc(-100% + .9375rem) ;--_ui5-v2-5-0_timeline_tli_indicator_after_height: calc(100% - .75rem) ;--_ui5-v2-5-0_timeline_tli_horizontal_indicator_after_left: 1.8625rem;--_ui5-v2-5-0_timeline_tli_horizontal_indicator_short_after_width: calc(100% - 1rem) ;--_ui5-v2-5-0_timeline_tli_without_icon_horizontal_indicator_before_width: calc(100% - .625rem) ;--_ui5-v2-5-0_timeline_tli_last_child_vertical_indicator_before_height: calc(100% - 2.5rem) ;--_ui5-v2-5-0_timeline_tlgi_compact_icon_before_height: calc(100% + 1.5rem) ;--_ui5-v2-5-0_timeline_tlgi_horizontal_line_placeholder_before_width: var(--_ui5-v2-5-0_timeline_tlgi_compact_icon_before_height);--_ui5-v2-5-0_timeline_tlgi_horizontal_compact_root_margin_left: .5rem;--_ui5-v2-5-0_timeline_tlgi_compact_root_gap: .5rem;--_ui5-v2-5-0_timeline_tlgi_root_horizontal_height: 19.375rem;--_ui5-v2-5-0_vsd_header_container: 2.5rem;--_ui5-v2-5-0_vsd_sub_header_container_height: 2rem;--_ui5-v2-5-0_vsd_header_height: 4rem;--_ui5-v2-5-0_vsd_expand_content_height: 25.4375rem;--_ui5-v2-5-0-toolbar-separator-height: 1.5rem;--_ui5-v2-5-0-toolbar-height: 2rem;--_ui5-v2-5-0_toolbar_overflow_padding: .1875rem .375rem;--_ui5-v2-5-0_dynamic_page_title_actions_separator_height: var(--_ui5-v2-5-0-toolbar-separator-height);--_ui5-v2-5-0_textarea_padding_top: .1875rem;--_ui5-v2-5-0_textarea_padding_bottom: .125rem;--_ui5-v2-5-0_checkbox_focus_position: .25rem;--_ui5-v2-5-0_split_button_middle_separator_top: .3125rem;--_ui5-v2-5-0_split_button_middle_separator_height: 1rem;--_ui5-v2-5-0_slider_handle_top: -.5rem;--_ui5-v2-5-0_slider_tooltip_height: 1.375rem;--_ui5-v2-5-0_checkbox_wrapped_focus_inset_block: .125rem;--_ui5-v2-5-0_color-palette-item-height: 1.25rem;--_ui5-v2-5-0_color-palette-item-focus-height: 1rem;--_ui5-v2-5-0_color-palette-item-container-sides-padding: .1875rem;--_ui5-v2-5-0_color-palette-item-container-rows-padding: .8125rem;--_ui5-v2-5-0_color-palette-item-hover-height: 1.625rem;--_ui5-v2-5-0_color-palette-item-margin: calc(((var(--_ui5-v2-5-0_color-palette-item-hover-height) - var(--_ui5-v2-5-0_color-palette-item-height)) / 2) + .0625rem);--_ui5-v2-5-0_color-palette-row-width: 8.75rem;--_ui5-v2-5-0_color-palette-swatch-container-padding: .1875rem .5rem;--_ui5-v2-5-0_color-palette-item-hover-margin: .0625rem;--_ui5-v2-5-0_color-palette-row-height: 7.5rem;--_ui5-v2-5-0_color-palette-button-height: 2rem;--_ui5-v2-5-0_color-palette-item-before-focus-inset: -.25rem;--_ui5-v2-5-0_color_picker_slider_container_margin_top: -9px;--_ui5-v2-5-0_daypicker_selected_item_now_special_day_top: 1.5625rem;--_ui5-v2-5-0_daypicker_specialday_focused_top: 1.3125rem;--_ui5-v2-5-0_daypicker_selected_item_now_special_day_border_bottom_radius_alternate: .5rem;--_ui5-v2-5-0_daypicker_specialday_focused_border_bottom: .25rem;--_ui5-v2-5-0_daypicker_item_now_specialday_top: 1.4375rem;--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_padding_block: 0 .375rem;--_ui5-v2-5-0_dp_two_calendar_item_secondary_text_padding: 0 .375rem;--_ui5-v2-5-0_daypicker_two_calendar_item_selected_focus_margin_bottom: -.25rem;--_ui5-v2-5-0_daypicker_two_calendar_item_selected_focus_padding_right: .4375rem}:root,[dir=ltr]{--_ui5-v2-5-0_rotation_90deg: rotate(90deg);--_ui5-v2-5-0_rotation_minus_90deg: rotate(-90deg);--_ui5-v2-5-0_icon_transform_scale: none;--_ui5-v2-5-0_panel_toggle_btn_rotation: var(--_ui5-v2-5-0_rotation_90deg);--_ui5-v2-5-0_li_notification_group_toggle_btn_rotation: var(--_ui5-v2-5-0_rotation_90deg);--_ui5-v2-5-0_timeline_scroll_container_offset: .5rem;--_ui5-v2-5-0_popover_upward_arrow_margin: .1875rem 0 0 .1875rem;--_ui5-v2-5-0_popover_right_arrow_margin: .1875rem 0 0 -.375rem;--_ui5-v2-5-0_popover_downward_arrow_margin: -.375rem 0 0 .125rem;--_ui5-v2-5-0_popover_left_arrow_margin: .125rem 0 0 .25rem;--_ui5-v2-5-0_dialog_resize_cursor: se-resize;--_ui5-v2-5-0_progress_indicator_bar_border_radius: .5rem 0 0 .5rem;--_ui5-v2-5-0_progress_indicator_remaining_bar_border_radius: 0 .5rem .5rem 0;--_ui5-v2-5-0_menu_submenu_margin_offset: -.25rem 0;--_ui5-v2-5-0_menu_submenu_placement_type_left_margin_offset: .25rem 0;--_ui5-v2-5-0-menu_item_icon_float: right;--_ui5-v2-5-0-shellbar-notification-btn-count-offset: -.125rem}[dir=rtl],[dir=rtl] :host{--_ui5-v2-5-0_icon_transform_scale: scale(-1, 1);--_ui5-v2-5-0_panel_toggle_btn_rotation: var(--_ui5-v2-5-0_rotation_minus_90deg);--_ui5-v2-5-0_li_notification_group_toggle_btn_rotation: var(--_ui5-v2-5-0_rotation_minus_90deg);--_ui5-v2-5-0_timeline_scroll_container_offset: -.5rem;--_ui5-v2-5-0_popover_upward_arrow_margin: .1875rem .125rem 0 0;--_ui5-v2-5-0_popover_right_arrow_margin: .1875rem .25rem 0 0;--_ui5-v2-5-0_popover_downward_arrow_margin: -.4375rem .125rem 0 0;--_ui5-v2-5-0_popover_left_arrow_margin: .1875rem -.375rem 0 0;--_ui5-v2-5-0_dialog_resize_cursor:sw-resize;--_ui5-v2-5-0_progress_indicator_bar_border_radius: 0 .5rem .5rem 0;--_ui5-v2-5-0_progress_indicator_remaining_bar_border_radius: .5rem 0 0 .5rem;--_ui5-v2-5-0_menu_submenu_margin_offset: 0 -.25rem;--_ui5-v2-5-0_menu_submenu_placement_type_left_margin_offset: 0 .25rem;--_ui5-v2-5-0-menu_item_icon_float: left;--_ui5-v2-5-0_segmented_btn_item_border_left: .0625rem;--_ui5-v2-5-0_segmented_btn_item_border_right: 0px;--_ui5-v2-5-0-shellbar-notification-btn-count-offset: auto} ` }; - registerThemePropertiesLoader("@ui5/webcomponents-theming", "sap_horizon", async () => styleData$4); - registerThemePropertiesLoader("@ui5/webcomponents", "sap_horizon", async () => styleData$3); + f$8("@ui5/webcomponents-theming", "sap_horizon", async () => styleData$4); + f$8("@ui5/webcomponents", "sap_horizon", async () => styleData$3); const styleData$2 = { packageName: "@ui5/webcomponents", fileName: "themes/Icon.css.ts", content: `:host{-webkit-tap-highlight-color:rgba(0,0,0,0)}:host([hidden]){display:none}:host([invalid]){display:none}:host(:not([hidden]).ui5_hovered){opacity:.7}:host{display:inline-block;width:1rem;height:1rem;color:var(--sapContent_IconColor);fill:currentColor;outline:none}:host([design="Contrast"]){color:var(--sapContent_ContrastIconColor)}:host([design="Critical"]){color:var(--sapCriticalElementColor)}:host([design="Information"]){color:var(--sapInformativeElementColor)}:host([design="Negative"]){color:var(--sapNegativeElementColor)}:host([design="Neutral"]){color:var(--sapNeutralElementColor)}:host([design="NonInteractive"]){color:var(--sapContent_NonInteractiveIconColor)}:host([design="Positive"]){color:var(--sapPositiveElementColor)}:host([mode="Interactive"][desktop]) .ui5-icon-root:focus,:host([mode="Interactive"]) .ui5-icon-root:focus-visible{outline:var(--sapContent_FocusWidth) var(--sapContent_FocusStyle) var(--sapContent_FocusColor);border-radius:var(--ui5-v2-5-0-icon-focus-border-radius)}.ui5-icon-root{display:flex;height:100%;width:100%;outline:none;vertical-align:top}:host([mode="Interactive"]){cursor:pointer}.ui5-icon-root:not([dir=ltr]){transform:var(--_ui5-v2-5-0_icon_transform_scale);transform-origin:center} ` }; @@ -4042,7 +356,7 @@ sap.ui.define((function () { 'use strict'; return (c > 3 && r && Object.defineProperty(target, key, r), r); }); const ICON_NOT_FOUND = "ICON_NOT_FOUND"; - let Icon = class Icon extends UI5Element { + let Icon = class Icon extends S$1 { constructor() { super(...arguments); this.design = "Default"; @@ -4055,15 +369,15 @@ sap.ui.define((function () { 'use strict'; if (this.mode !== IconMode$1.Interactive) { return; } - if (isEnter(e)) { + if (b(e)) { this.fireDecoratorEvent("click"); } - if (isSpace(e)) { + if (i$2(e)) { e.preventDefault(); } } _onkeyup(e) { - if (this.mode === IconMode$1.Interactive && isSpace(e)) { + if (this.mode === IconMode$1.Interactive && i$2(e)) { this.fireDecoratorEvent("click"); } } @@ -4087,7 +401,7 @@ sap.ui.define((function () { 'use strict'; } } onEnterDOM() { - if (isDesktop()) { + if (f$b()) { this.setAttribute("desktop", ""); } } @@ -4096,9 +410,9 @@ sap.ui.define((function () { 'use strict'; if (!name) { return console.warn("Icon name property is required", this); } - let iconData = getIconDataSync(name); + let iconData = u(name); if (!iconData) { - iconData = await getIconData(name); + iconData = await n(name); } if (!iconData) { this.invalid = true; @@ -4111,7 +425,7 @@ sap.ui.define((function () { 'use strict'; this.viewBox = iconData.viewBox || "0 0 512 512"; if (iconData.customTemplate) { iconData.pathData = []; - this.customSvg = executeTemplate(iconData.customTemplate, this); + this.customSvg = l$8(iconData.customTemplate, this); } this.invalid = false; this.pathData = Array.isArray(iconData.pathData) ? iconData.pathData : [iconData.pathData]; @@ -4121,7 +435,7 @@ sap.ui.define((function () { 'use strict'; if (this.accessibleName) { this.effectiveAccessibleName = this.accessibleName; } else if (this.accData) { - const i18nBundle = await getI18nBundle(this.packageName); + const i18nBundle = await f$5(this.packageName); this.effectiveAccessibleName = i18nBundle.getText(this.accData) || undefined; } else { this.effectiveAccessibleName = undefined; @@ -4131,34 +445,34 @@ sap.ui.define((function () { 'use strict'; return this.showTooltip && this.effectiveAccessibleName; } }; - __decorate$2([property()], Icon.prototype, "design", void 0); - __decorate$2([property()], Icon.prototype, "name", void 0); - __decorate$2([property()], Icon.prototype, "accessibleName", void 0); - __decorate$2([property({ + __decorate$2([s$4()], Icon.prototype, "design", void 0); + __decorate$2([s$4()], Icon.prototype, "name", void 0); + __decorate$2([s$4()], Icon.prototype, "accessibleName", void 0); + __decorate$2([s$4({ type: Boolean })], Icon.prototype, "showTooltip", void 0); - __decorate$2([property()], Icon.prototype, "mode", void 0); - __decorate$2([property({ + __decorate$2([s$4()], Icon.prototype, "mode", void 0); + __decorate$2([s$4({ type: Array })], Icon.prototype, "pathData", void 0); - __decorate$2([property({ + __decorate$2([s$4({ type: Object, noAttribute: true })], Icon.prototype, "accData", void 0); - __decorate$2([property({ + __decorate$2([s$4({ type: Boolean })], Icon.prototype, "invalid", void 0); - __decorate$2([property({ + __decorate$2([s$4({ noAttribute: true })], Icon.prototype, "effectiveAccessibleName", void 0); - Icon = __decorate$2([customElement({ + Icon = __decorate$2([m$4({ tag: "ui5-icon", languageAware: true, themeAware: true, - renderer: litRender, + renderer: l$1, template: block0$2, styles: styleData$2 - }), event("click", { + }), l$5("click", { bubbles: true })], Icon); Icon.define(); @@ -4171,10 +485,10 @@ sap.ui.define((function () { 'use strict'; const FORM_CHECKABLE_REQUIRED = { key: "FORM_CHECKABLE_REQUIRED", defaultText: "Please tick this box if you want to proceed." }; /* eslint no-unused-vars: 0 */ - function block0$1(context, tags, suffix) { return effectiveHtml ``; } + function block0$1(context, tags, suffix) { return m$1 ``; } - registerThemePropertiesLoader("@ui5/webcomponents-theming", "sap_horizon", async () => styleData$4); - registerThemePropertiesLoader("@ui5/webcomponents", "sap_horizon", async () => styleData$3); + f$8("@ui5/webcomponents-theming", "sap_horizon", async () => styleData$4); + f$8("@ui5/webcomponents", "sap_horizon", async () => styleData$3); const styleData$1 = { packageName: "@ui5/webcomponents", fileName: "themes/Label.css.ts", content: `:host(:not([hidden])){display:inline-flex}:host{max-width:100%;color:var(--sapContent_LabelColor);font-family:"72override",var(--sapFontFamily);font-size:var(--sapFontSize);font-weight:400;cursor:text}.ui5-label-root{width:100%;cursor:inherit}:host{white-space:normal}:host([wrapping-type="None"]){white-space:nowrap}:host([wrapping-type="None"]) .ui5-label-root{display:inline-flex}:host([wrapping-type="None"]) .ui5-label-text-wrapper{text-overflow:ellipsis;overflow:hidden;display:inline-block;vertical-align:top;flex:0 1 auto;min-width:0}:host([show-colon]) .ui5-label-required-colon:before{content:attr(data-colon)}:host([required]) .ui5-label-required-colon:after{content:"*";color:var(--sapField_RequiredColor);font-size:1.25rem;font-weight:700;position:relative;font-style:normal;vertical-align:middle;line-height:0}.ui5-label-text-wrapper{padding-inline-end:.075rem}:host([required][show-colon]) .ui5-label-required-colon:after{margin-inline-start:.125rem}:host([show-colon]) .ui5-label-required-colon{margin-inline-start:-.05rem;white-space:pre} ` }; @@ -4184,7 +498,7 @@ sap.ui.define((function () { 'use strict'; return (c > 3 && r && Object.defineProperty(target, key, r), r); }); var Label_1; - let Label = Label_1 = class Label extends UI5Element { + let Label = Label_1 = class Label extends S$1 { constructor() { super(...arguments); this.showColon = false; @@ -4204,18 +518,18 @@ sap.ui.define((function () { 'use strict'; return Label_1.i18nBundle.getText(LABEL_COLON); } }; - __decorate$1([property()], Label.prototype, "for", void 0); - __decorate$1([property({ + __decorate$1([s$4()], Label.prototype, "for", void 0); + __decorate$1([s$4({ type: Boolean })], Label.prototype, "showColon", void 0); - __decorate$1([property({ + __decorate$1([s$4({ type: Boolean })], Label.prototype, "required", void 0); - __decorate$1([property()], Label.prototype, "wrappingType", void 0); - __decorate$1([i18n("@ui5/webcomponents")], Label, "i18nBundle", void 0); - Label = Label_1 = __decorate$1([customElement({ + __decorate$1([s$4()], Label.prototype, "wrappingType", void 0); + __decorate$1([i$3("@ui5/webcomponents")], Label, "i18nBundle", void 0); + Label = Label_1 = __decorate$1([m$4({ tag: "ui5-label", - renderer: litRender, + renderer: l$1, template: block0$1, styles: styleData$1, languageAware: true @@ -4223,18 +537,18 @@ sap.ui.define((function () { 'use strict'; Label.define(); var Label$1 = Label; - registerThemePropertiesLoader("@ui5/webcomponents-theming", "sap_horizon", async () => styleData$4); - registerThemePropertiesLoader("@ui5/webcomponents", "sap_horizon", async () => styleData$3); + f$8("@ui5/webcomponents-theming", "sap_horizon", async () => styleData$4); + f$8("@ui5/webcomponents", "sap_horizon", async () => styleData$3); const styleData = { packageName: "@ui5/webcomponents", fileName: "themes/CheckBox.css.ts", content: `.ui5-hidden-text{position:absolute;clip:rect(1px,1px,1px,1px);user-select:none;left:-1000px;top:-1000px;pointer-events:none;font-size:0}:host{-webkit-tap-highlight-color:rgba(0,0,0,0)}:host(:not([hidden])){display:inline-block}:host{overflow:hidden;max-width:100%;outline:none;border-radius:var(--_ui5-v2-5-0_checkbox_border_radius);transition:var(--_ui5-v2-5-0_checkbox_transition);cursor:pointer;user-select:none;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none}:host([disabled]){cursor:default}:host([disabled]) .ui5-checkbox-root{opacity:var(--_ui5-v2-5-0_checkbox_disabled_opacity)}:host([disabled]) .ui5-checkbox-inner{border-color:var(--_ui5-v2-5-0_checkbox_inner_disabled_border_color)}:host([disabled]) .ui5-checkbox-label{color:var(--_ui5-v2-5-0_checkbox_disabled_label_color)}:host([readonly]:not([value-state="Critical"]):not([value-state="Negative"])) .ui5-checkbox-inner{background:var(--sapField_ReadOnly_Background);border:var(--_ui5-v2-5-0_checkbox_inner_readonly_border);color:var(--sapField_TextColor)}:host(:not([wrapping-type="None"])[text]) .ui5-checkbox-root{min-height:auto;box-sizing:border-box;align-items:flex-start;padding-top:var(--_ui5-v2-5-0_checkbox_root_side_padding);padding-bottom:var(--_ui5-v2-5-0_checkbox_root_side_padding)}:host(:not([wrapping-type="None"])[text]) .ui5-checkbox-root .ui5-checkbox-label{overflow-wrap:break-word;align-self:center}:host([desktop][text]:not([wrapping-type="None"])) .ui5-checkbox-root:focus:before,.ui5-checkbox-root[text]:focus-visible:before{inset-block:var(--_ui5-v2-5-0_checkbox_wrapped_focus_inset_block)}:host([value-state="Negative"]) .ui5-checkbox-inner,:host([value-state="Negative"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--sapField_InvalidBackground);border:var(--_ui5-v2-5-0_checkbox_inner_error_border);color:var(--sapField_InvalidColor)}:host([value-state="Negative"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--_ui5-v2-5-0_checkbox_inner_error_background_hover)}:host([value-state="Critical"]) .ui5-checkbox-inner,:host([value-state="Critical"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--sapField_WarningBackground);border:var(--_ui5-v2-5-0_checkbox_inner_warning_border);color:var(--_ui5-v2-5-0_checkbox_inner_warning_color)}:host([value-state="Critical"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--_ui5-v2-5-0_checkbox_inner_warning_background_hover)}:host([value-state="Information"]) .ui5-checkbox-inner,:host([value-state="Information"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--sapField_InformationBackground);border:var(--_ui5-v2-5-0_checkbox_inner_information_border);color:var(--_ui5-v2-5-0_checkbox_inner_information_color)}:host([value-state="Information"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--_ui5-v2-5-0_checkbox_inner_information_background_hover)}:host([value-state="Positive"]) .ui5-checkbox-inner,:host([value-state="Positive"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--sapField_SuccessBackground);border:var(--_ui5-v2-5-0_checkbox_inner_success_border);color:var(--sapField_SuccessColor)}:host([value-state="Positive"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--_ui5-v2-5-0_checkbox_inner_success_background_hover)}:host([value-state="Critical"]) .ui5-checkbox-icon,:host([value-state="Critical"][indeterminate]) .ui5-checkbox-inner:after{color:var(--_ui5-v2-5-0_checkbox_checkmark_warning_color)}.ui5-checkbox-root{position:relative;display:inline-flex;align-items:center;width:100%;min-height:var(--_ui5-v2-5-0_checkbox_width_height);min-width:var(--_ui5-v2-5-0_checkbox_width_height);padding:0 var(--_ui5-v2-5-0_checkbox_wrapper_padding);outline:none;transition:var(--_ui5-v2-5-0_checkbox_transition);border:var(--_ui5-v2-5-0_checkbox_default_focus_border);border-radius:var(--_ui5-v2-5-0_checkbox_border_radius);box-sizing:border-box}:host([desktop]) .ui5-checkbox-root:focus:before,.ui5-checkbox-root:focus-visible:before{display:var(--_ui5-v2-5-0_checkbox_focus_outline_display);content:"";position:absolute;inset-inline:var(--_ui5-v2-5-0_checkbox_focus_position);inset-block:var(--_ui5-v2-5-0_checkbox_focus_position);border:var(--_ui5-v2-5-0_checkbox_focus_outline);border-radius:var(--_ui5-v2-5-0_checkbox_focus_border_radius)}:host([text]) .ui5-checkbox-root{padding-inline-end:var(--_ui5-v2-5-0_checkbox_right_focus_distance)}:host([text]) .ui5-checkbox-root:focus:before,:host([text]) .ui5-checkbox-root:focus-visible:before{inset-inline-end:0}:host(:hover:not([disabled])){background:var(--_ui5-v2-5-0_checkbox_outer_hover_background)}.ui5-checkbox--hoverable .ui5-checkbox-label:hover{color:var(--_ui5-v2-5-0_checkbox_label_color)}:host(:not([active]):not([checked]):not([value-state])) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner,:host(:not([active]):not([checked])[value-state="None"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--_ui5-v2-5-0_checkbox_hover_background);border-color:var(--_ui5-v2-5-0_checkbox_inner_hover_border_color)}:host(:not([active])[checked]:not([value-state])) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner,:host(:not([active])[checked][value-state="None"]) .ui5-checkbox--hoverable:hover .ui5-checkbox-inner{background:var(--_ui5-v2-5-0_checkbox_hover_background);border-color:var(--_ui5-v2-5-0_checkbox_inner_hover_checked_border_color)}:host([checked]:not([value-state])) .ui5-checkbox-inner,:host([checked][value-state="None"]) .ui5-checkbox-inner{border-color:var(--_ui5-v2-5-0_checkbox_inner_selected_border_color)}:host([active]:not([checked]):not([value-state]):not([disabled])) .ui5-checkbox-inner,:host([active]:not([checked])[value-state="None"]:not([disabled])) .ui5-checkbox-inner{border-color:var(--_ui5-v2-5-0_checkbox_inner_active_border_color);background-color:var(--_ui5-v2-5-0_checkbox_active_background)}:host([active][checked]:not([value-state]):not([disabled])) .ui5-checkbox-inner,:host([active][checked][value-state="None"]:not([disabled])) .ui5-checkbox-inner{border-color:var(--_ui5-v2-5-0_checkbox_inner_selected_border_color);background-color:var(--_ui5-v2-5-0_checkbox_active_background)}.ui5-checkbox-inner{min-width:var(--_ui5-v2-5-0_checkbox_inner_width_height);max-width:var(--_ui5-v2-5-0_checkbox_inner_width_height);height:var(--_ui5-v2-5-0_checkbox_inner_width_height);max-height:var(--_ui5-v2-5-0_checkbox_inner_width_height);border:var(--_ui5-v2-5-0_checkbox_inner_border);border-radius:var(--_ui5-v2-5-0_checkbox_inner_border_radius);background:var(--_ui5-v2-5-0_checkbox_inner_background);color:var(--_ui5-v2-5-0_checkbox_checkmark_color);box-sizing:border-box;position:relative;cursor:inherit}:host([indeterminate][checked]) .ui5-checkbox-inner:after{content:"";background-color:currentColor;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:var(--_ui5-v2-5-0_checkbox_partially_icon_size);height:var(--_ui5-v2-5-0_checkbox_partially_icon_size)}:host input{-webkit-appearance:none;visibility:hidden;width:0;left:0;position:absolute;font-size:inherit}.ui5-checkbox-root .ui5-checkbox-label{margin-inline-start:var(--_ui5-v2-5-0_checkbox_label_offset);cursor:inherit;text-overflow:ellipsis;overflow:hidden;pointer-events:none;color:var(--_ui5-v2-5-0_checkbox_label_color)}.ui5-checkbox-icon{width:var(--_ui5-v2-5-0_checkbox_icon_size);height:var(--_ui5-v2-5-0_checkbox_icon_size);color:currentColor;cursor:inherit;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%)}:host([display-only]){cursor:default}:host([display-only]) .ui5-checkbox-display-only-icon-inner [ui5-icon]{color:var(--sapTextColor)}:host([display-only]) .ui5-checkbox-display-only-icon-inner{min-width:var(--_ui5-v2-5-0_checkbox_inner_width_height);max-width:var(--_ui5-v2-5-0_checkbox_inner_width_height);height:var(--_ui5-v2-5-0_checkbox_inner_width_height);max-height:var(--_ui5-v2-5-0_checkbox_inner_width_height);display:flex;align-items:center;justify-content:center} ` }; /* eslint no-unused-vars: 0 */ - function block0(context, tags, suffix) { return effectiveHtml ``; } - function block1(context, tags, suffix) { return suffix ? effectiveHtml `
<${scopeTag("ui5-icon", tags, suffix)} aria-hidden="true" name=${l(this.displayOnlyIcon)} class="ui5-checkbox-display-only-icon" part="icon">
` : effectiveHtml `
`; } - function block2(context, tags, suffix) { return effectiveHtml `
${this.isCompletelyChecked ? block3.call(this, context, tags, suffix) : undefined}
`; } - function block3(context, tags, suffix) { return suffix ? effectiveHtml `<${scopeTag("ui5-icon", tags, suffix)} aria-hidden="true" name="accept" class="ui5-checkbox-icon" part="icon">` : effectiveHtml ``; } - function block4(context, tags, suffix) { return suffix ? effectiveHtml `<${scopeTag("ui5-label", tags, suffix)} part="label" id="${l(this._id)}-label" class="ui5-checkbox-label" wrapping-type="${l(this.wrappingType)}">${l(this.text)}` : effectiveHtml `${l(this.text)}`; } - function block5(context, tags, suffix) { return effectiveHtml `${l(this.valueStateText)}`; } + function block0(context, tags, suffix) { return m$1 ``; } + function block1(context, tags, suffix) { return suffix ? m$1 `
<${f$1("ui5-icon", tags, suffix)} aria-hidden="true" name=${l$2(this.displayOnlyIcon)} class="ui5-checkbox-display-only-icon" part="icon">
` : m$1 `
`; } + function block2(context, tags, suffix) { return m$1 `
${this.isCompletelyChecked ? block3.call(this, context, tags, suffix) : undefined}
`; } + function block3(context, tags, suffix) { return suffix ? m$1 `<${f$1("ui5-icon", tags, suffix)} aria-hidden="true" name="accept" class="ui5-checkbox-icon" part="icon">` : m$1 ``; } + function block4(context, tags, suffix) { return suffix ? m$1 `<${f$1("ui5-label", tags, suffix)} part="label" id="${l$2(this._id)}-label" class="ui5-checkbox-label" wrapping-type="${l$2(this.wrappingType)}">${l$2(this.text)}` : m$1 `${l$2(this.text)}`; } + function block5(context, tags, suffix) { return m$1 `${l$2(this.valueStateText)}`; } var __decorate = this && this.__decorate || (function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; @@ -4244,7 +558,7 @@ sap.ui.define((function () { 'use strict'; var CheckBox_1; let isGlobalHandlerAttached = false; let activeCb; - let CheckBox = CheckBox_1 = class CheckBox extends UI5Element { + let CheckBox = CheckBox_1 = class CheckBox extends S$1 { get formValidityMessage() { return CheckBox_1.i18nBundle.getText(FORM_CHECKABLE_REQUIRED); } @@ -4281,7 +595,7 @@ sap.ui.define((function () { 'use strict'; } } onEnterDOM() { - if (isDesktop()) { + if (f$b()) { this.setAttribute("desktop", ""); } } @@ -4302,19 +616,19 @@ sap.ui.define((function () { 'use strict'; this.active = false; } _onkeydown(e) { - if (isSpace(e)) { + if (i$2(e)) { e.preventDefault(); } if (this.readonly || this.disabled) { return; } - if (isEnter(e)) { + if (b(e)) { this.toggle(); } this.active = true; } _onkeyup(e) { - if (isSpace(e)) { + if (i$2(e)) { this.toggle(); } this.active = false; @@ -4351,12 +665,12 @@ sap.ui.define((function () { 'use strict'; }; } get ariaLabelText() { - return getEffectiveAriaLabelText(this); + return A(this); } get classes() { return { main: { - "ui5-checkbox--hoverable": !this.disabled && !this.readonly && isDesktop() + "ui5-checkbox--hoverable": !this.disabled && !this.readonly && f$b() } }; } @@ -4379,10 +693,10 @@ sap.ui.define((function () { 'use strict'; return this.hasValueState ? `${this._id}-descr` : undefined; } get hasValueState() { - return this.valueState !== ValueState$1.None; + return this.valueState !== o.None; } get valueStateText() { - if (this.valueState !== ValueState$1.None && this.valueState !== ValueState$1.Information) { + if (this.valueState !== o.None && this.valueState !== o.Information) { return this.valueStateTextMappings()[this.valueState]; } } @@ -4406,46 +720,46 @@ sap.ui.define((function () { 'use strict'; return "border"; } }; - __decorate([property()], CheckBox.prototype, "accessibleNameRef", void 0); - __decorate([property()], CheckBox.prototype, "accessibleName", void 0); - __decorate([property({ + __decorate([s$4()], CheckBox.prototype, "accessibleNameRef", void 0); + __decorate([s$4()], CheckBox.prototype, "accessibleName", void 0); + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "disabled", void 0); - __decorate([property({ + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "readonly", void 0); - __decorate([property({ + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "displayOnly", void 0); - __decorate([property({ + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "required", void 0); - __decorate([property({ + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "indeterminate", void 0); - __decorate([property({ + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "checked", void 0); - __decorate([property()], CheckBox.prototype, "text", void 0); - __decorate([property()], CheckBox.prototype, "valueState", void 0); - __decorate([property()], CheckBox.prototype, "wrappingType", void 0); - __decorate([property()], CheckBox.prototype, "name", void 0); - __decorate([property({ + __decorate([s$4()], CheckBox.prototype, "text", void 0); + __decorate([s$4()], CheckBox.prototype, "valueState", void 0); + __decorate([s$4()], CheckBox.prototype, "wrappingType", void 0); + __decorate([s$4()], CheckBox.prototype, "name", void 0); + __decorate([s$4({ type: Boolean })], CheckBox.prototype, "active", void 0); - __decorate([i18n("@ui5/webcomponents")], CheckBox, "i18nBundle", void 0); - CheckBox = CheckBox_1 = __decorate([customElement({ + __decorate([i$3("@ui5/webcomponents")], CheckBox, "i18nBundle", void 0); + CheckBox = CheckBox_1 = __decorate([m$4({ tag: "ui5-checkbox", languageAware: true, formAssociated: true, - renderer: litRender, + renderer: l$1, template: block0, styles: styleData, dependencies: [Label$1, Icon$1] - }), event("change", { + }), l$5("change", { bubbles: true, cancelable: true - }), event("value-changed", { + }), l$5("value-changed", { bubbles: true, cancelable: true })], CheckBox); diff --git a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/app.js b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/app.js index b8be1288..3ca885db 100644 --- a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/app.js +++ b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/app.js @@ -1,45 +1,50 @@ -sap.ui.define(['ui5/ecosystem/demo/app/resources/index.cjs3'], (function (index_cjs$1) { 'use strict'; - - var index_cjs = {}; - - (function (exports) { - - Object.defineProperty(exports, '__esModule', { value: true }); - - var app = index_cjs$1.index_cjs; - - var name = "firebase"; - var version = "11.0.1"; - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - app.registerVersion(name, version, 'app'); - - Object.keys(app).forEach(function (k) { - if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return app[k]; } - }); - }); - - } (index_cjs)); - - let exp = index_cjs?.default || index_cjs || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} - - return exp; +sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index.esm2017'], (function (exports, index_esm2017) { 'use strict'; + + var name = "firebase"; + var version = "11.0.1"; + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + index_esm2017.registerVersion(name, version, 'app'); + + const __esModule = true; + + exports.FirebaseError = index_esm2017.FirebaseError; + exports.SDK_VERSION = index_esm2017.SDK_VERSION; + exports._DEFAULT_ENTRY_NAME = index_esm2017.DEFAULT_ENTRY_NAME; + exports._addComponent = index_esm2017._addComponent; + exports._addOrOverwriteComponent = index_esm2017._addOrOverwriteComponent; + exports._apps = index_esm2017._apps; + exports._clearComponents = index_esm2017._clearComponents; + exports._components = index_esm2017._components; + exports._getProvider = index_esm2017._getProvider; + exports._isFirebaseApp = index_esm2017._isFirebaseApp; + exports._isFirebaseServerApp = index_esm2017._isFirebaseServerApp; + exports._registerComponent = index_esm2017._registerComponent; + exports._removeServiceInstance = index_esm2017._removeServiceInstance; + exports._serverApps = index_esm2017._serverApps; + exports.deleteApp = index_esm2017.deleteApp; + exports.getApp = index_esm2017.getApp; + exports.getApps = index_esm2017.getApps; + exports.initializeApp = index_esm2017.initializeApp; + exports.initializeServerApp = index_esm2017.initializeServerApp; + exports.onLog = index_esm2017.onLog; + exports.registerVersion = index_esm2017.registerVersion; + exports.setLogLevel = index_esm2017.setLogLevel; + exports.__esModule = __esModule; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/firestore/lite.js b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/firestore/lite.js index 9abafb4e..368fe069 100644 --- a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/firestore/lite.js +++ b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/firestore/lite.js @@ -1,12258 +1,7426 @@ -sap.ui.define(['ui5/ecosystem/demo/app/resources/index.cjs3'], (function (index_cjs$1) { 'use strict'; +sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index.esm2017'], (function (exports, index_esm2017) { 'use strict'; + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ + class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } + } + + /** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), + // TODO(mikelehen): Look into getting a proper uid-equivalent for + // non-FirebaseAuth providers. + User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), + User.MOCK_USER = new User("mock-user"); + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + let d = "11.0.0"; + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + const f = new index_esm2017.index_cjs.Logger("@firebase/firestore"); + + /** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + f.setLogLevel(t); + } + + function __PRIVATE_logDebug(t, ...e) { + if (f.logLevel <= index_esm2017.index_cjs.LogLevel.DEBUG) { + const r = e.map(__PRIVATE_argToString); + f.debug(`Firestore (${d}): ${t}`, ...r); + } + } + + function __PRIVATE_logError(t, ...e) { + if (f.logLevel <= index_esm2017.index_cjs.LogLevel.ERROR) { + const r = e.map(__PRIVATE_argToString); + f.error(`Firestore (${d}): ${t}`, ...r); + } + } + + /** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (f.logLevel <= index_esm2017.index_cjs.LogLevel.WARN) { + const r = e.map(__PRIVATE_argToString); + f.warn(`Firestore (${d}): ${t}`, ...r); + } + } + + /** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + */ function fail(t = "Unexpected state") { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + const e = `FIRESTORE (${d}) INTERNAL ASSERTION FAILED: ` + t; + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(e), new Error(e); + } + + /** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + */ function __PRIVATE_hardAssert(t, e) { + t || fail(); + } + + /** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e) { + return t; + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ const E = "ok", m = "cancelled", A = "unknown", T = "invalid-argument", R = "deadline-exceeded", P = "not-found", V = "already-exists", I = "permission-denied", p = "unauthenticated", y = "resource-exhausted", w = "failed-precondition", g = "aborted", F = "out-of-range", v = "unimplemented", D = "internal", b = "unavailable", C = "data-loss"; + + /** An error returned by a Firestore operation. */ class FirestoreError extends index_esm2017.FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } + } + + /** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} + } + + /** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } + } + + /** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken), + new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} + } + + /* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.t = t, this.i = e, this.o = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.u = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ l() { + return this.o ? this.o() : null; + } + get headers() { + this.u.set("X-Goog-AuthUser", this.t); + // Use array notation to prevent minification + const t = this.l(); + return t && this.u.set("Authorization", t), this.i && this.u.set("X-Goog-Iam-Authorization-Token", this.i), + this.u; + } + } + + /* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.t = t, this.i = e, this.o = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.t, this.i, this.o)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} + } + + class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } + } + + /** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(t) { + this.h = t, this.appCheck = null, t.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token), + new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} + } + + /** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u; + } + } + + /** The default database name for a project. */ + /** + * Represents the database ID a Firestore client is associated with. + * @internal + */ + class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || "(default)"; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return "(default)" === this.database; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } + } + + /** + * Path represents an ordered sequence of string segments. + */ + class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(), void 0 === r ? r = t.length - e : r > t.length - e && fail(), + this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.get(n), i = e.get(n); + if (r < i) return -1; + if (r > i) return 1; + } + return t.length < e.length ? -1 : t.length > e.length ? 1 : 0; + } + } + + /** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(T, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } + } + + const S = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + + /** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return S.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && "__name__" === this.get(0); + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ "__name__" ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(T, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(T, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(T, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(T, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(T, `Function ${t}() cannot be called with an empty ${e}.`); + } + + /** + * Validates that two boolean options are not set at the same time. + * @internal + */ + /** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ + function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(T, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); + } + + /** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(T, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); + } + + /** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ + /** Returns a string describing the type / value of the provided input. */ + function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(); + } + + function __PRIVATE_cast(t, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(T, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(T, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; + } + + function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(T, `Function ${t}() requires a positive number, but it was: ${e}.`); + } + + /** + * @license + * Copyright 2023 Google LLC + * + * 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. + */ + /** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ + /** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ + function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; + } + + /** + * @license + * Copyright 2023 Google LLC + * + * 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. + */ + /** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let N = null; + + /** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ + /** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ + function __PRIVATE_generateUniqueDebugId() { + return null === N ? N = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : N++, "0x" + N.toString(16); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; + } + + /** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; + } + + /** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + const O = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" + }; + + /** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ + var q, B; + + /** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ + function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + A; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return E; + + case 400: + // Bad Request + return w; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return p; + + case 403: + // Forbidden + return I; + + case 404: + // Not Found + return P; + + case 409: + // Conflict + return g; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return F; + + case 429: + // Too Many Requests + return y; + + case 499: + // Client Closed Request + return m; + + case 500: + // Internal Server Error + return A; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return v; + + case 503: + // Service Unavailable + return b; + + case 504: + // Gateway Timeout + return R; + + default: + return t >= 200 && t < 300 ? E : t >= 400 && t < 500 ? w : t >= 500 && t < 600 ? D : A; + } + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (B = q || (q = {}))[B.OK = 0] = "OK", B[B.CANCELLED = 1] = "CANCELLED", B[B.UNKNOWN = 2] = "UNKNOWN", + B[B.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", B[B.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", + B[B.NOT_FOUND = 5] = "NOT_FOUND", B[B.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", B[B.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", + B[B.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", B[B.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", + B[B.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", B[B.ABORTED = 10] = "ABORTED", + B[B.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", B[B.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", + B[B.INTERNAL = 13] = "INTERNAL", B[B.UNAVAILABLE = 14] = "UNAVAILABLE", B[B.DATA_LOSS = 15] = "DATA_LOSS"; + + class __PRIVATE_FetchConnection extends + /** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ + class __PRIVATE_RestConnection { + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.m = e + "://" + t.host, this.A = `projects/${r}/databases/${n}`, this.T = "(default)" === this.databaseId.database ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + get R() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + P(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.V(t, e.toUriEncodedString()); + __PRIVATE_logDebug("RestConnection", `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.A, + "x-goog-request-params": this.T + }; + return this.I(a, n, i), this.p(t, o, a, r).then((e => (__PRIVATE_logDebug("RestConnection", `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn("RestConnection", `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + g(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.P(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ I(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + d; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + V(t, e) { + const r = O[t]; + return `${this.m}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } + } { + F(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async p(t, e, r, n) { + var i; + const s = JSON.stringify(n); + let o; + try { + o = await fetch(e, { + method: "POST", + headers: r, + body: s + }); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = null === (i = null == t ? void 0 : t.error) || void 0 === i ? void 0 : i.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${null != e ? e : o.statusText}`); + } + return o.json(); + } + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** Initializes the HTTP connection for the REST API. */ + /** + * @license + * Copyright 2023 Google LLC + * + * 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. + */ + /** + * Concrete implementation of the Aggregate type. + */ + class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length; + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % t.length)); + } + return r; + } + } + + function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; + } + + /** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; + } + + function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); + } + + /** + * @license + * Copyright 2023 Google LLC + * + * 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. + */ + /** + * An error encountered while decoding base64 string. + */ + class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** Converts a Base64 encoded string to a binary string. */ + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ + class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = function __PRIVATE_decodeBase64(t) { + try { + return atob(t); + } catch (t) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && t instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } + } + /** Converts a binary string to a Base64 encoded string. */ (t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + return btoa(t); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } + } + + ByteString.EMPTY_BYTE_STRING = new ByteString(""); + + const $ = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + + /** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = $.exec(t); + if (__PRIVATE_hardAssert(!!r), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; + } + + /** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; + } + + /** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). + /** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ + class Timestamp { + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(T, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(T, "Timestamp nanoseconds out of range: " + e); + if (t < -62135596800) throw new FirestoreError(T, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(T, "Timestamp seconds out of range: " + t); + } + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor(1e6 * (t - 1e3 * e)); + return new Timestamp(e, r); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / 1e6; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() { + return { + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - -62135596800; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ function __PRIVATE_isServerTimestamp(t) { + var e, r; + return "server_timestamp" === (null === (r = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === r ? void 0 : r.stringValue); + } + + /** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; + } + + /** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ const Q = { + fields: { + __type__: { + stringValue: "__max__" + } + } + }; + + /** Extracts the backend's type order for the provided value. */ + function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue; + } + /** + * @license + * Copyright 2022 Google LLC + * + * 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. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + var e, r; + return "__vector__" === (null === (r = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === r ? void 0 : r.stringValue); + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(); + } + + /** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(); + } + } + + function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); + } + + function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_primitiveComparator(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + var r, n, i, s; + const o = t.fields || {}, a = e.fields || {}, u = null === (r = o.value) || void 0 === r ? void 0 : r.arrayValue, _ = null === (n = a.value) || void 0 === n ? void 0 : n.arrayValue, c = __PRIVATE_primitiveComparator((null === (i = null == u ? void 0 : u.values) || void 0 === i ? void 0 : i.length) || 0, (null === (s = null == _ ? void 0 : _.values) || void 0 === s ? void 0 : s.length) || 0); + if (0 !== c) return c; + return __PRIVATE_compareArrays(u, _); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === Q && e === Q) return 0; + if (t === Q) return 1; + if (e === Q) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_primitiveComparator(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(); + } + } + + function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); + } + + function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + } + + function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; + } + + /** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; + } + + /** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; + } + + /** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); + } + + /** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; + } + + function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: Object.assign({}, t.geoPointValue) + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: Object.assign({}, t.timestampValue) + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return Object.assign({}, t); + } + + class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } + } + + function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; + } + + /** + * @license + * Copyright 2022 Google LLC + * + * 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. + */ class Filter {} + + class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } + } + + class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.v = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.v || (this.v = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.v; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } + } + + function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(); + } + + class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } + } + + /** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } + } + + /** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } + } + + function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + var r; + return ((null === (r = e.arrayValue) || void 0 === r ? void 0 : r.values) || []).map((t => DocumentKey.fromName(t.referenceValue))); + } + + /** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } + } + + /** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } + } + + /** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } + } + + /** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } + } + + /** + * @license + * Copyright 2022 Google LLC + * + * 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. + */ + /** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } + } + + function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + constructor(t) { + this.timestamp = t; + } + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + // An immutable sorted map implementation, based on a Left-leaning Red-Black + // tree. + class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } + } + + // end SortedMap + // An iterator over an LLRBNode. + class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } + } + + // end SortedMapIterator + // Represents a node in a Left-leaning Red-Black tree. + class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(); + if (this.right.isRed()) throw fail(); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(); + return t + (this.isRed() ? 0 : 1); + } + } + + // end LLRBNode + // Empty node is shared between all LLRB trees. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + + // end LLRBEmptyNode + LLRBNode.EMPTY = new + // Represents an empty node (a leaf node in the Red-Black Tree). + class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(); + } + get value() { + throw fail(); + } + get color() { + throw fail(); + } + get left() { + throw fail(); + } + get right() { + throw fail(); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } + }; + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ + class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } + } + + class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } + } + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + // Visible for testing + class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.D = null; + } + } + + /** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ + class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.C = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.S = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.N = null, this.startAt, this.endAt; + } + } + + /** Creates a new Query for a query that matches all documents at `path` */ + /** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ + function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; + } + + /** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.C) { + e.C = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.C.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.C.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.C.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.C; + } + + /** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.S || (e.S = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.S; + } + + /** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } + } + + function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); + } + + function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; + } + + /** + * Returns an IntegerValue for `value`. + */ + /** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ + function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); + } + + /** + * @license + * Copyright 2018 Google LLC + * + * 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. + */ + /** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } + } + + /** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + + /** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } + } + + /** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } + } + + /** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.O = e; + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } + } + + /** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } + } + + /** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + + /** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } + } + + /** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } + } + + /** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } + } + + /** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ const L = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; + })(), M = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; + })(), x = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; + })(); + + /** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ + class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } + } + + /** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ + /** + * Returns a value for a Date that's appropriate to put into a proto. + */ + function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; + } + + /** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ + function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); + } + + function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); + } + + function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); + } + + function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); + } + + function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); + } + + function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); + } + + function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e)), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(T, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(T, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4)), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); + } + + function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; + } + + function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing), __PRIVATE_hardAssert(!!e.readTime); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(); + } + + function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.O + }; + throw fail(); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(); + }(t, e.precondition)), r; + } + + function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + q: r, + parent: i + }; + } + + function __PRIVATE_toDirection(t) { + return L[t]; + } + + // visible for testing + function __PRIVATE_toOperatorName(t) { + return M[t]; + } + + function __PRIVATE_toCompositeOperatorName(t) { + return x[t]; + } + + function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; + } + + function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(); + } + + function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; + } + + function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ + class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.B = t, this.timerId = e, this.$ = r, this.L = n, this.M = i, this.k = 0, this.U = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.j = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.k = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ W() { + this.k = this.M; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ K(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.k + this.G()), r = Math.max(0, Date.now() - this.j), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.k} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.U = this.B.enqueueAfterDelay(this.timerId, n, (() => (this.j = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.k *= this.L, this.k < this.$ && (this.k = this.$), this.k > this.M && (this.k = this.M); + } + H() { + null !== this.U && (this.U.skipDelay(), this.U = null); + } + cancel() { + null !== this.U && (this.U.cancel(), this.U = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ G() { + return (Math.random() - .5) * this.k; + } + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ + /** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ + class __PRIVATE_DatastoreImpl extends class Datastore {} { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.J = !1; + } + Y() { + if (this.J) throw new FirestoreError(w, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ P(t, e, r, n) { + return this.Y(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.P(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === p && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(A, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ g(t, e, r, n, i) { + return this.Y(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.g(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === p && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(A, t.toString()); + })); + } + terminate() { + this.J = !0, this.connection.terminate(); + } + } - var index_cjs = {}; - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; + // TODO(firestorexp): Make sure there is only one Datastore instance per + // firestore-exp client. + async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.P("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); + } + + async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.g("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e), o.push(e); + })), o; + } + + async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {q: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.g("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); + } + + async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + var n; + const i = __PRIVATE_debugCast(t), {request: s, Z: o, parent: a} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {q: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + Z: o, + parent: s + }; + }(i.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.N || ( + // Do not include implicit order-bys for aggregate queries. + e.N = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.N; + }(e), r); + i.connection.R || delete s.parent; + const u = (await i.g("RunAggregationQuery", i.serializer.databaseId, a, s, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === u.length); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const _ = null === (n = u[0].result) || void 0 === n ? void 0 : n.aggregateFields; + return Object.keys(_).reduce(((t, e) => (t[o[e]] = _[e], t)), {}); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ const k = new Map; + + /** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ + /** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ + function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(w, "The client has already been terminated."); + if (!k.has(t)) { + __PRIVATE_logDebug("ComponentProvider", "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams); + } + /** + * @license + * Copyright 2018 Google LLC + * + * 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. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + k.set(t, n); + } + return k.get(t); + } + + /** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ + /** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ + class FirestoreSettingsImpl { + constructor(t) { + var e, r; + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(T, "Can't provide ssl option if host option is not set"); + this.host = "firestore.googleapis.com", this.ssl = true; + } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e; + if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, + this.localCache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new FirestoreError(T, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(T, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (r = t.experimentalLongPollingOptions) && void 0 !== r ? r : {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(T, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(T, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(T, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } - - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; + class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(w, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(w, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(T, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = k.get(t); + e && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), k.delete(t), + e.terminate()); + }(this), Promise.resolve(); + } + } - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + function initializeFirestore(t, e, r) { + r || (r = "(default)"); + const n = index_esm2017._getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(w, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); + } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') - } - - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } - - parts.push(output); - - return parts.join('') - } - - function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; - } - - var toString = {}.toString; - - var isArray$2 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - - var INSPECT_MAX_BYTES = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = index_cjs$1.global.TYPED_ARRAY_SUPPORT !== undefined - ? index_cjs$1.global.TYPED_ARRAY_SUPPORT - : true; - - /* - * Export kMaxLength after typed array support is determined. - */ - kMaxLength(); - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length); - } - that.length = length; - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192; // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; - return arr - }; - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - }; - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) ; - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } + function getFirestore(e, r) { + const n = "object" == typeof e ? e : index_esm2017.getApp(), i = "string" == typeof e ? e : r || "(default)", s = index_esm2017._getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = index_esm2017.getDefaultEmulatorHostnameAndPort("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; + } + + /** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + var i; + const s = (t = __PRIVATE_cast(t, Firestore))._getSettings(), o = `${e}:${r}`; + if ("firestore.googleapis.com" !== s.host && s.host !== o && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."), + t._setSettings(Object.assign(Object.assign({}, s), { + host: o, + ssl: !1 + })), n.mockUserToken) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = index_esm2017.createMockUserToken(n.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId); + const s = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!s) throw new FirestoreError(T, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(s); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } } - return that - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; + /** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), index_esm2017._removeServiceInstance(t.app, "firestore/lite"), t._delete(); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * @license + * Copyright 2022 Google LLC + * + * 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. + */ + /** + * Represents an aggregation that can be performed by Firestore. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } + } - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + /** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } + } - var actual = that.write(string, encoding); + /** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + } - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); + /** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } } - return that - } - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + function collection(t, e, ...r) { + if (t = index_esm2017.getModularInstance(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(T, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } + } - if (that.length === 0) { - return that - } + // TODO(firestorelite): Consider using ErrorFactory - + // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 + /** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(T, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); + } + + function doc(t, e, ...r) { + if (t = index_esm2017.getModularInstance(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(T, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } + } - obj.copy(that, 0, 0, len); - return that + /** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = index_esm2017.getModularInstance(t), e = index_esm2017.getModularInstance(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); + } + + /** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = index_esm2017.getModularInstance(t), e = index_esm2017.getModularInstance(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(T, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(T, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); } - return fromArrayLike(that, obj) - } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } + } - if (obj.type === 'Buffer' && isArray$2(obj.data)) { - return fromArrayLike(that, obj.data) - } + /** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath("__name__"); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(T, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(T, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() { + return { + latitude: this._lat, + longitude: this._long + }; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + } - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + /** + * @license + * Copyright 2024 Google LLC + * + * 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. + */ + /** + * Represents a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ + class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } } - return length | 0 - } - Buffer.isBuffer = isBuffer$1; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) - } - Buffer.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - }; - - Buffer.concat = function concat (list, length) { - if (!isArray$2(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; - - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer.byteLength = byteLength; - - function slowToString (encoding, start, end) { - var loweredCase = false; - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8'; - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ const U = /^__.*__$/; + + /** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } + /** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } } - } - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true; + function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; - Buffer.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') + default: + throw fail(); + } } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); + + /** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.X(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get tt() { + return this.settings.tt; + } + /** Returns a new context with the specified settings overwritten. */ et(t) { + return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + rt(t) { + var e; + const r = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), n = this.et({ + path: r, + nt: !1 + }); + return n.it(t), n; + } + st(t) { + var e; + const r = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), n = this.et({ + path: r, + nt: !1 + }); + return n.X(), n; + } + ot(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.et({ + path: void 0, + nt: !0 + }); + } + ut(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings._t || !1, this.path, this.settings.ct); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + X() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.it(this.path.get(t)); + } + it(t) { + if (0 === t.length) throw this.ut("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.tt) && U.test(t)) throw this.ut('Document fields cannot begin and end with "__"'); + } } - return this - }; - Buffer.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') + /** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ lt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + tt: t, + methodName: e, + ct: r, + path: FieldPath$1.emptyPath(), + nt: !1, + _t: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); + + function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); } - return this - }; - Buffer.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') + /** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.lt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(T, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); + + class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.tt) throw 1 /* UserDataSource.Update */ === t.tt ? t.ut(`${this._methodName}() can only appear at the top level of your update data`) : t.ut(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } } - return this - }; - Buffer.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; + /** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + tt: 3 /* UserDataSource.Argument */ , + ct: e.settings.ct, + methodName: t._methodName, + nt: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); + } + + class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } + } - Buffer.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - }; + class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.ht = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.ht.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && index_esm2017.deepEqual(this.ht, t.ht); + } + } - Buffer.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; + class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.ht = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.ht.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && index_esm2017.deepEqual(this.ht, t.ht); + } } - return '' - }; - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') + + class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.dt = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.dt)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.dt === t.dt; + } } - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - - if (this === target) return 0 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8'; - - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - }; - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; + /** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.lt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = index_esm2017.getModularInstance(n); + const u = i.st(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); + } + + /** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.lt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(T, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = index_esm2017.getModularInstance(r); + const n = o.st(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } + } + const h = new FieldMask(_); + return new ParsedUpdateData(c, h, o.fieldTransforms); + } + + /** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.lt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); + } + + /** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = index_esm2017.getModularInstance(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.tt)) throw e.ut(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ut(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings.nt && 4 /* UserDataSource.ArrayArgument */ !== e.tt) throw e.ut("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ot(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = index_esm2017.getModularInstance(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ut(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + return { + mapValue: { + fields: { + __type__: { + stringValue: "__vector__" + }, + value: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ut("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + } + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ut(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); + } + + function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.rt(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; + } - res.push(codePoint); - i += bytesPerSequence; + function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); } - return decodeCodePointsArray(res) - } + function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); + }(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ut(t + " a custom object") : e.ut(t + " " + n); + } + } - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000; + /** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = index_esm2017.getModularInstance(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } + + /** + * Matches any characters in a field path string that are reserved. + */ const j = new RegExp("[~\\*/\\[\\]]"); + + /** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(j) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } + } - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(T, a + t + u); + } + + /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); + /** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } } - return res - } - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + /** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } + } - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); + /** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = index_esm2017.getModularInstance(t), e = index_esm2017.getModularInstance(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); + } + + /** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ + class AppliableConstraint {} + + /** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + + function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(T, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; + } + + /** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(T, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + return FieldFilter.create(i, s, a); + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } } - return ret - } - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + /** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); + } + + /** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } + } - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); + /** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); + } + + /** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); + } + + /** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(T, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(T, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + return new OrderBy(e, r); + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } } - return ret - } - function hexSlice (buf, start, end) { - var len = buf.length; + /** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); + } + + /** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } + } - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + /** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); + } + + /** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); + } + + /** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } + } - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); + function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); } - return out - } - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); } - return res - } - Buffer.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + /** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } + } - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; + function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); + } + + function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); + } + + /** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = index_esm2017.getModularInstance(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(P, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(T, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(T, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(T, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(T, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(T, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(T, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; + function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = index_esm2017.getModularInstance(r))) { + if ("" === r) throw new FirestoreError(T, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(T, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(T, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(T, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); + } + + /** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(T, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); + } + + /** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(T, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(T, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); + } + + function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(T, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ + function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; + } + + class __PRIVATE_LiteUserDataWriter extends class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + var e, r, n; + const i = null === (n = null === (r = null === (e = t.fields) || void 0 === e ? void 0 : e.value.arrayValue) || void 0 === r ? void 0 : r.values) || void 0 === n ? void 0 : n.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(i); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); - var newBuf; - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r)); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } + } { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } } - return newBuf - }; - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } + /** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); + } + + /** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(v, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); + } + + function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); + } + + function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = index_esm2017.getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); + } + + /** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); + } + + /** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); + } + + /** + * @license + * Copyright 2022 Google LLC + * + * 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. + */ + /** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); + } + + /** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t); + return new AggregateQuerySnapshot(e, n, r); + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); + } + + function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); + } + + /** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); + } + + /** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); + } + + /** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + var r, n; + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && (null === (r = t._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString()) === (null === (n = e._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()); + } + + /** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && index_esm2017.deepEqual(t.data(), e.data()); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); + } + + /** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); + } + + /** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); + } + + /** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); + } + + /** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); + } + + /** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); + } + + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = index_esm2017.getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(w, "A write batch can no longer be used after commit() has been called."); + } + } - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + function __PRIVATE_validateReference(t, e) { + if ((t = index_esm2017.getModularInstance(t)).firestore !== e) throw new FirestoreError(T, "Provided document reference is from a different Firestore instance."); + return t; + } + + /** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(T, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(g, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(T, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} + } + + /** + * @license + * Copyright 2022 Google LLC + * + * 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. + */ const z = { + maxAttempts: 5 + }; - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + /** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ + class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.ft = r.maxAttempts, this.Et = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ At() { + this.ft -= 1, this.Tt(); + } + Tt() { + this.Et.K((async () => { + const t = new Transaction$1(this.datastore), e = this.Rt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Pt(t); + })))); + })).catch((t => { + this.Pt(t); + })); + })); + } + Rt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Pt(t) { + this.ft > 0 && this.Vt(t) ? (this.ft -= 1, this.asyncQueue.enqueueAndForget((() => (this.Tt(), + Promise.resolve())))) : this.deferred.reject(t); + } + Vt(t) { + if ("FirebaseError" === t.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + default: + return fail(); + + case m: + case A: + case R: + case y: + case D: + case b: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case p: + return !1; + + case T: + case P: + case V: + case I: + case w: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case g: + case F: + case v: + case C: + return !0; + } + }(e); + } + return !1; + } } - return val - }; - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + /** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; + } + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(m, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.It = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.yt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.wt = [], + // visible for testing + this.gt = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Ft = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.vt = !1, + // List of TimerIds to fast-forward delays for. + this.Dt = [], + // Backoff timer used to schedule retries for retryable operations + this.Et = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug("AsyncQueue", "Visibility state changed to " + t.visibilityState), + this.Et.H(); + }, this.Ct = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.bt); + } + get isShuttingDown() { + return this.yt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.St(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.Nt(t); + } + enterRestrictedMode(t) { + if (!this.yt) { + this.yt = !0, this.vt = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.bt); + } + } + enqueue(t) { + if (this.St(), this.yt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.Nt((() => this.yt && this.vt ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.It.push(t), this.Ot()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Ot() { + if (0 !== this.It.length) { + try { + await this.It[0](), this.It.shift(), this.Et.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + } + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ (t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug("AsyncQueue", "Operation failed with retryable error: " + t); + } + this.It.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.Et.K((() => this.Ot())); + } + } + Nt(t) { + const e = this.Ct.then((() => (this.Ft = !0, t().catch((t => { + this.gt = t, this.Ft = !1; + const e = + /** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ + function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * 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. + */ + // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the + // legacy SDK. + /** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ (t); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", e), t; + })).then((t => (this.Ft = !1, t)))))); + return this.Ct = e, e; + } + enqueueAfterDelay(t, e, r) { + this.St(), + // Fast-forward delays for timerIds that have been overridden. + this.Dt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.qt(t))); + return this.wt.push(n), n; + } + St() { + this.gt && fail(); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Bt() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.Ct, await t; + } while (t !== this.Ct); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ $t(t) { + for (const e of this.wt) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ Qt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Bt().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.wt.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.wt) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Bt(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Lt(t) { + this.Dt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ qt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.wt.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.wt.splice(e, 1); + } } - return val - }; + class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = index_esm2017.getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } + } - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; - - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - - if (!val) val = 0; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } - - // valid lead - leadSurrogate = codePoint; - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray - } - - - function base64ToBytes (str) { - return toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) - } - - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } - - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) - } - - var index_node_cjs = {}; - - var inherits; - if (typeof Object.create === 'function'){ - inherits = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - var inherits$1 = inherits; - - var getOwnPropertyDescriptors = - Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(" "); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (x === "%%") return "%"; - if (i >= len) return x; - switch (x) { - case "%s": - return String(args[i++]); - case "%d": - return Number(args[i++]); - case "%j": - try { - return JSON.stringify(args[i++]); - } catch (_) { - return "[Circular]"; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += " " + x; - } else { - str += " " + inspect(x); - } - } - return str; - } - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(index_cjs$1.global.process)) { - return function () { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - if (index_cjs$1.browser$1.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (index_cjs$1.browser$1.throwDeprecation) { - throw new Error(msg); - } else if (index_cjs$1.browser$1.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - } - - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) debugEnviron = index_cjs$1.browser$1.env.NODE_DEBUG || ""; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp("\\b" + set + "\\b", "i").test(debugEnviron)) { - var pid = 0; - debugs[set] = function () { - var msg = format.apply(null, arguments); - console.error("%s %d: %s", set, pid, msg); - }; - } else { - debugs[set] = function () {}; - } - } - return debugs[set]; - } - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor, - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - bold: [1, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - white: [37, 39], - grey: [90, 39], - black: [30, 39], - blue: [34, 39], - cyan: [36, 39], - green: [32, 39], - magenta: [35, 39], - red: [31, 39], - yellow: [33, 39], - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - special: "cyan", - number: "yellow", - boolean: "yellow", - undefined: "grey", - null: "bold", - string: "green", - date: "magenta", - // "name": intentionally not styling - regexp: "red", - }; - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return "\u001b[" + inspect.colors[style][0] + "m" + str + "\u001b[" + inspect.colors[style][1] + "m"; - } else { - return str; - } - } - - function stylizeNoColor(str, styleType) { - return str; - } - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function (val, idx) { - hash[val] = true; - }); - - return hash; - } - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if ( - ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value) - ) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ": " + value.name : ""; - return ctx.stylize("[Function" + name + "]", "special"); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), "date"); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = "", - array = false, - braces = ["{", "}"]; - - // Make Array say that they are Array - if (isArray$1(value)) { - array = true; - braces = ["[", "]"]; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ": " + value.name : ""; - base = " [Function" + n + "]"; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = " " + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = " " + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = " " + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); - } else { - return ctx.stylize("[Object]", "special"); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function (key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) return ctx.stylize("undefined", "undefined"); - if (isString(value)) { - var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; - return ctx.stylize(simple, "string"); - } - if (isNumber(value)) return ctx.stylize("" + value, "number"); - if (isBoolean(value)) return ctx.stylize("" + value, "boolean"); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) return ctx.stylize("null", "null"); - } - - function formatError(value) { - return "[" + Error.prototype.toString.call(value) + "]"; - } - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); - } else { - output.push(""); - } - } - keys.forEach(function (key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); - } - }); - return output; - } - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize("[Getter/Setter]", "special"); - } else { - str = ctx.stylize("[Getter]", "special"); - } - } else { - if (desc.set) { - str = ctx.stylize("[Setter]", "special"); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = "[" + key + "]"; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf("\n") > -1) { - if (array) { - str = str - .split("\n") - .map(function (line) { - return " " + line; - }) - .join("\n") - .substr(2); - } else { - str = - "\n" + - str - .split("\n") - .map(function (line) { - return " " + line; - }) - .join("\n"); - } - } - } else { - str = ctx.stylize("[Circular]", "special"); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify("" + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, "name"); - } else { - name = name - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, "string"); - } - } - - return name + ": " + str; - } - - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function (prev, cur) { - if (cur.indexOf("\n") >= 0) ; - return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; - }, 0); - - if (length > 60) { - return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1]; - } - - return braces[0] + base + " " + output.join(", ") + " " + braces[1]; - } - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$1(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === "boolean"; - } - - function isNull(arg) { - return arg === null; - } - - function isNullOrUndefined$1(arg) { - return arg == null; - } - - function isNumber(arg) { - return typeof arg === "number"; - } - - function isString(arg) { - return typeof arg === "string"; - } - - function isSymbol(arg) { - return typeof arg === "symbol"; - } - - function isUndefined(arg) { - return arg === void 0; - } - - function isRegExp(re) { - return isObject(re) && objectToString(re) === "[object RegExp]"; - } - - function isObject(arg) { - return typeof arg === "object" && arg !== null; - } - - function isDate(d) { - return isObject(d) && objectToString(d) === "[object Date]"; - } - - function isError(e) { - return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error); - } - - function isFunction(arg) { - return typeof arg === "function"; - } - - function isPrimitive(arg) { - return ( - arg === null || - typeof arg === "boolean" || - typeof arg === "number" || - typeof arg === "string" || - typeof arg === "symbol" || // ES6 symbol - typeof arg === "undefined" - ); - } - - function isBuffer(maybeBuf) { - return Buffer.isBuffer(maybeBuf); - } - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - function pad(n) { - return n < 10 ? "0" + n.toString(10) : n.toString(10); - } - - var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":"); - return [d.getDate(), months[d.getMonth()], time].join(" "); - } - - // log is just a thin wrapper to console.log that prepends a timestamp - function log() { - console.log("%s - %s", timestamp(), format.apply(null, arguments)); - } - - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - } - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : undefined; - - function promisify(original) { - if (typeof original !== "function") throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== "function") { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, - enumerable: false, - writable: false, - configurable: true, - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, - enumerable: false, - writable: false, - configurable: true, - }); - return Object.defineProperties(fn, getOwnPropertyDescriptors(original)); - } - - promisify.custom = kCustomPromisifiedSymbol; - - function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error("Promise was rejected with a falsy value"); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); - } - - function callbackify(original) { - if (typeof original !== "function") { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== "function") { - throw new TypeError("The last argument must be of type Function"); - } - var self = this; - var cb = function () { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args).then( - function (ret) { - index_cjs$1.browser$1.nextTick(cb.bind(null, null, ret)); - }, - function (rej) { - index_cjs$1.browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); - } - ); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); - return callbackified; - } - - function isPromise(obj) { - return obj && typeof obj.then === "function"; - } - - const types = { - inherits: inherits$1, - _extend: _extend, - log: log, - isBuffer: isBuffer, - isPrimitive: isPrimitive, - isFunction: isFunction, - isError: isError, - isDate: isDate, - isObject: isObject, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol, - isString: isString, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined$1, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray$1, - inspect: inspect, - deprecate: deprecate, - format: format, - debuglog: debuglog, - promisify: promisify, - callbackify: callbackify, - isPromise: isPromise, - }; - - const TextEncoder = (function () { - return globalThis.TextEncoder || require("util").TextEncoder; - })(); // ### MODIFIED ### - const TextDecoder = (function () { - return globalThis.TextDecoder || require("util").TextDecoder; - })(); // ### MODIFIED ### - - var _polyfillNode_util = /*#__PURE__*/Object.freeze({ - __proto__: null, - TextDecoder: TextDecoder, - TextEncoder: TextEncoder, - _extend: _extend, - callbackify: callbackify, - debuglog: debuglog, - default: types, - deprecate: deprecate, - format: format, - inherits: inherits$1, - inspect: inspect, - isArray: isArray$1, - isBoolean: isBoolean, - isBuffer: isBuffer, - isDate: isDate, - isError: isError, - isFunction: isFunction, - isNull: isNull, - isNullOrUndefined: isNullOrUndefined$1, - isNumber: isNumber, - isObject: isObject, - isPrimitive: isPrimitive, - isPromise: isPromise, - isRegExp: isRegExp, - isString: isString, - isSymbol: isSymbol, - isUndefined: isUndefined, - log: log, - promisify: promisify, - types: types - }); - - var require$$3 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_util); - - var _polyfillNode_crypto = {}; - - var _polyfillNode_crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - default: _polyfillNode_crypto - }); - - var require$$5 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_crypto$1); - - Object.defineProperty(index_node_cjs, '__esModule', { value: true }); - - var app = index_cjs$1.index_cjs; - var component = index_cjs$1.index_cjs$2; - var logger = index_cjs$1.index_cjs$1; - var util$1 = require$$3; - var util = index_cjs$1.require$$4; - var crypto = require$$5; - - const version$1 = "4.7.4"; - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Simple wrapper around a nullable UID. Mostly exists to make code more - * readable. - */ - class User { - constructor(uid) { - this.uid = uid; - } - isAuthenticated() { - return this.uid != null; - } - /** - * Returns a key representing this user, suitable for inclusion in a - * dictionary. - */ - toKey() { - if (this.isAuthenticated()) { - return 'uid:' + this.uid; - } - else { - return 'anonymous-user'; - } - } - isEqual(otherUser) { - return otherUser.uid === this.uid; - } - } - /** A user with a null UID. */ - User.UNAUTHENTICATED = new User(null); - // TODO(mikelehen): Look into getting a proper uid-equivalent for - // non-FirebaseAuth providers. - User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); - User.FIRST_PARTY = new User('first-party-uid'); - User.MOCK_USER = new User('mock-user'); - - const version = "11.0.0"; - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - let SDK_VERSION = version; - function setSDKVersion(version) { - SDK_VERSION = version; - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** Formats an object as a JSON string, suitable for logging. */ - function formatJSON(value) { - // util.inspect() results in much more readable output than JSON.stringify() - return util$1.inspect(value, { depth: 100 }); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - const logClient = new logger.Logger('@firebase/firestore'); - /** - * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). - * - * @param logLevel - The verbosity you set for activity and error logging. Can - * be any of the following values: - * - *
    - *
  • `debug` for the most verbose logging level, primarily for - * debugging.
  • - *
  • `error` to log errors only.
  • - *
  • `silent` to turn off logging.
  • - *
- */ - function setLogLevel(logLevel) { - logClient.setLogLevel(logLevel); - } - function logDebug(msg, ...obj) { - if (logClient.logLevel <= logger.LogLevel.DEBUG) { - const args = obj.map(argToString); - logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); - } - } - function logError(msg, ...obj) { - if (logClient.logLevel <= logger.LogLevel.ERROR) { - const args = obj.map(argToString); - logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); - } - } - /** - * @internal - */ - function logWarn(msg, ...obj) { - if (logClient.logLevel <= logger.LogLevel.WARN) { - const args = obj.map(argToString); - logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); - } - } - /** - * Converts an additional log parameter to a string representation. - */ - function argToString(obj) { - if (typeof obj === 'string') { - return obj; - } - else { - try { - return formatJSON(obj); - } - catch (e) { - // Converting to JSON failed, just log the object directly - return obj; - } - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Unconditionally fails, throwing an Error with the given message. - * Messages are stripped in production builds. - * - * Returns `never` and can be used in expressions: - * @example - * let futureVar = fail('not implemented yet'); - */ - function fail(failure = 'Unexpected state') { - // Log the failure in addition to throw an exception, just in case the - // exception is swallowed. - const message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure; - logError(message); - // NOTE: We don't use FirestoreError here because these are internal failures - // that cannot be handled by the user. (Also it would create a circular - // dependency between the error and assert modules which doesn't work.) - throw new Error(message); - } - /** - * Fails if the given assertion condition is false, throwing an Error with the - * given message if it did. - * - * Messages are stripped in production builds. - */ - function hardAssert(assertion, message) { - if (!assertion) { - fail(); - } - } - /** - * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an - * instance of `T` before casting. - */ - function debugCast(obj, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor) { - return obj; - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - const Code = { - // Causes are copied from: - // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h - /** Not an error; returned on success. */ - OK: 'ok', - /** The operation was cancelled (typically by the caller). */ - CANCELLED: 'cancelled', - /** Unknown error or an error from a different error domain. */ - UNKNOWN: 'unknown', - /** - * Client specified an invalid argument. Note that this differs from - * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are - * problematic regardless of the state of the system (e.g., a malformed file - * name). - */ - INVALID_ARGUMENT: 'invalid-argument', - /** - * Deadline expired before operation could complete. For operations that - * change the state of the system, this error may be returned even if the - * operation has completed successfully. For example, a successful response - * from a server could have been delayed long enough for the deadline to - * expire. - */ - DEADLINE_EXCEEDED: 'deadline-exceeded', - /** Some requested entity (e.g., file or directory) was not found. */ - NOT_FOUND: 'not-found', - /** - * Some entity that we attempted to create (e.g., file or directory) already - * exists. - */ - ALREADY_EXISTS: 'already-exists', - /** - * The caller does not have permission to execute the specified operation. - * PERMISSION_DENIED must not be used for rejections caused by exhausting - * some resource (use RESOURCE_EXHAUSTED instead for those errors). - * PERMISSION_DENIED must not be used if the caller cannot be identified - * (use UNAUTHENTICATED instead for those errors). - */ - PERMISSION_DENIED: 'permission-denied', - /** - * The request does not have valid authentication credentials for the - * operation. - */ - UNAUTHENTICATED: 'unauthenticated', - /** - * Some resource has been exhausted, perhaps a per-user quota, or perhaps the - * entire file system is out of space. - */ - RESOURCE_EXHAUSTED: 'resource-exhausted', - /** - * Operation was rejected because the system is not in a state required for - * the operation's execution. For example, directory to be deleted may be - * non-empty, an rmdir operation is applied to a non-directory, etc. - * - * A litmus test that may help a service implementor in deciding - * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: - * (a) Use UNAVAILABLE if the client can retry just the failing call. - * (b) Use ABORTED if the client should retry at a higher-level - * (e.g., restarting a read-modify-write sequence). - * (c) Use FAILED_PRECONDITION if the client should not retry until - * the system state has been explicitly fixed. E.g., if an "rmdir" - * fails because the directory is non-empty, FAILED_PRECONDITION - * should be returned since the client should not retry unless - * they have first fixed up the directory by deleting files from it. - * (d) Use FAILED_PRECONDITION if the client performs conditional - * REST Get/Update/Delete on a resource and the resource on the - * server does not match the condition. E.g., conflicting - * read-modify-write on the same resource. - */ - FAILED_PRECONDITION: 'failed-precondition', - /** - * The operation was aborted, typically due to a concurrency issue like - * sequencer check failures, transaction aborts, etc. - * - * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, - * and UNAVAILABLE. - */ - ABORTED: 'aborted', - /** - * Operation was attempted past the valid range. E.g., seeking or reading - * past end of file. - * - * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed - * if the system state changes. For example, a 32-bit file system will - * generate INVALID_ARGUMENT if asked to read at an offset that is not in the - * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from - * an offset past the current file size. - * - * There is a fair bit of overlap between FAILED_PRECONDITION and - * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) - * when it applies so that callers who are iterating through a space can - * easily look for an OUT_OF_RANGE error to detect when they are done. - */ - OUT_OF_RANGE: 'out-of-range', - /** Operation is not implemented or not supported/enabled in this service. */ - UNIMPLEMENTED: 'unimplemented', - /** - * Internal errors. Means some invariants expected by underlying System has - * been broken. If you see one of these errors, Something is very broken. - */ - INTERNAL: 'internal', - /** - * The service is currently unavailable. This is a most likely a transient - * condition and may be corrected by retrying with a backoff. - * - * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, - * and UNAVAILABLE. - */ - UNAVAILABLE: 'unavailable', - /** Unrecoverable data loss or corruption. */ - DATA_LOSS: 'data-loss' - }; - /** An error returned by a Firestore operation. */ - class FirestoreError extends util.FirebaseError { - /** @hideconstructor */ - constructor( - /** - * The backend error code associated with this error. - */ - code, - /** - * A custom error description. - */ - message) { - super(code, message); - this.code = code; - this.message = message; - // HACK: We write a toString property directly because Error is not a real - // class and so inheritance does not work correctly. We could alternatively - // do the same "back-door inheritance" trick that FirebaseError does. - this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - class Deferred { - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - class OAuthToken { - constructor(value, user) { - this.user = user; - this.type = 'OAuth'; - this.headers = new Map(); - this.headers.set('Authorization', `Bearer ${value}`); - } - } - /** - * A CredentialsProvider that always yields an empty token. - * @internal - */ - class EmptyAuthCredentialsProvider { - getToken() { - return Promise.resolve(null); - } - invalidateToken() { } - start(asyncQueue, changeListener) { - // Fire with initial user. - asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); - } - shutdown() { } - } - /** - * A CredentialsProvider that always returns a constant token. Used for - * emulator token mocking. - */ - class EmulatorAuthCredentialsProvider { - constructor(token) { - this.token = token; - /** - * Stores the listener registered with setChangeListener() - * This isn't actually necessary since the UID never changes, but we use this - * to verify the listen contract is adhered to in tests. - */ - this.changeListener = null; - } - getToken() { - return Promise.resolve(this.token); - } - invalidateToken() { } - start(asyncQueue, changeListener) { - this.changeListener = changeListener; - // Fire with initial user. - asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); - } - shutdown() { - this.changeListener = null; - } - } - /** Credential provider for the Lite SDK. */ - class LiteAuthCredentialsProvider { - constructor(authProvider) { - this.auth = null; - authProvider.onInit(auth => { - this.auth = auth; - }); - } - getToken() { - if (!this.auth) { - return Promise.resolve(null); - } - return this.auth.getToken().then(tokenData => { - if (tokenData) { - hardAssert(typeof tokenData.accessToken === 'string'); - return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid())); - } - else { - return null; - } - }); - } - invalidateToken() { } - start(asyncQueue, changeListener) { } - shutdown() { } - } - /* - * FirstPartyToken provides a fresh token each time its value - * is requested, because if the token is too old, requests will be rejected. - * Technically this may no longer be necessary since the SDK should gracefully - * recover from unauthenticated errors (see b/33147818 for context), but it's - * safer to keep the implementation as-is. - */ - class FirstPartyToken { - constructor(sessionIndex, iamToken, authTokenFactory) { - this.sessionIndex = sessionIndex; - this.iamToken = iamToken; - this.authTokenFactory = authTokenFactory; - this.type = 'FirstParty'; - this.user = User.FIRST_PARTY; - this._headers = new Map(); - } - /** - * Gets an authorization token, using a provided factory function, or return - * null. - */ - getAuthToken() { - if (this.authTokenFactory) { - return this.authTokenFactory(); - } - else { - return null; - } - } - get headers() { - this._headers.set('X-Goog-AuthUser', this.sessionIndex); - // Use array notation to prevent minification - const authHeaderTokenValue = this.getAuthToken(); - if (authHeaderTokenValue) { - this._headers.set('Authorization', authHeaderTokenValue); - } - if (this.iamToken) { - this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); - } - return this._headers; - } - } - /* - * Provides user credentials required for the Firestore JavaScript SDK - * to authenticate the user, using technique that is only available - * to applications hosted by Google. - */ - class FirstPartyAuthCredentialsProvider { - constructor(sessionIndex, iamToken, authTokenFactory) { - this.sessionIndex = sessionIndex; - this.iamToken = iamToken; - this.authTokenFactory = authTokenFactory; - } - getToken() { - return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); - } - start(asyncQueue, changeListener) { - // Fire with initial uid. - asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); - } - shutdown() { } - invalidateToken() { } - } - class AppCheckToken { - constructor(value) { - this.value = value; - this.type = 'AppCheck'; - this.headers = new Map(); - if (value && value.length > 0) { - this.headers.set('x-firebase-appcheck', this.value); - } - } - } - /** AppCheck token provider for the Lite SDK. */ - class LiteAppCheckTokenProvider { - constructor(appCheckProvider) { - this.appCheckProvider = appCheckProvider; - this.appCheck = null; - appCheckProvider.onInit(appCheck => { - this.appCheck = appCheck; - }); - } - getToken() { - if (!this.appCheck) { - return Promise.resolve(null); - } - return this.appCheck.getToken().then(tokenResult => { - if (tokenResult) { - hardAssert(typeof tokenResult.token === 'string'); - return new AppCheckToken(tokenResult.token); - } - else { - return null; - } - }); - } - invalidateToken() { } - start(asyncQueue, changeListener) { } - shutdown() { } - } - /** - * Builds a CredentialsProvider depending on the type of - * the credentials passed in. - */ - function makeAuthCredentialsProvider(credentials) { - if (!credentials) { - return new EmptyAuthCredentialsProvider(); - } - switch (credentials['type']) { - case 'firstParty': - return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); - case 'provider': - return credentials['client']; - default: - throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - class DatabaseInfo { - /** - * Constructs a DatabaseInfo using the provided host, databaseId and - * persistenceKey. - * - * @param databaseId - The database to use. - * @param appId - The Firebase App Id. - * @param persistenceKey - A unique identifier for this Firestore's local - * storage (used in conjunction with the databaseId). - * @param host - The Firestore backend host to connect to. - * @param ssl - Whether to use SSL when connecting. - * @param forceLongPolling - Whether to use the forceLongPolling option - * when using WebChannel as the network transport. - * @param autoDetectLongPolling - Whether to use the detectBufferingProxy - * option when using WebChannel as the network transport. - * @param longPollingOptions Options that configure long-polling. - * @param useFetchStreams Whether to use the Fetch API instead of - * XMLHTTPRequest - */ - constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams) { - this.databaseId = databaseId; - this.appId = appId; - this.persistenceKey = persistenceKey; - this.host = host; - this.ssl = ssl; - this.forceLongPolling = forceLongPolling; - this.autoDetectLongPolling = autoDetectLongPolling; - this.longPollingOptions = longPollingOptions; - this.useFetchStreams = useFetchStreams; - } - } - /** The default database name for a project. */ - const DEFAULT_DATABASE_NAME = '(default)'; - /** - * Represents the database ID a Firestore client is associated with. - * @internal - */ - class DatabaseId { - constructor(projectId, database) { - this.projectId = projectId; - this.database = database ? database : DEFAULT_DATABASE_NAME; - } - static empty() { - return new DatabaseId('', ''); - } - get isDefaultDatabase() { - return this.database === DEFAULT_DATABASE_NAME; - } - isEqual(other) { - return (other instanceof DatabaseId && - other.projectId === this.projectId && - other.database === this.database); - } - } - function databaseIdFromApp(app, database) { - if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { - throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); - } - return new DatabaseId(app.options.projectId, database); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - const DOCUMENT_KEY_NAME = '__name__'; - /** - * Path represents an ordered sequence of string segments. - */ - class BasePath { - constructor(segments, offset, length) { - if (offset === undefined) { - offset = 0; - } - else if (offset > segments.length) { - fail(); - } - if (length === undefined) { - length = segments.length - offset; - } - else if (length > segments.length - offset) { - fail(); - } - this.segments = segments; - this.offset = offset; - this.len = length; - } - get length() { - return this.len; - } - isEqual(other) { - return BasePath.comparator(this, other) === 0; - } - child(nameOrPath) { - const segments = this.segments.slice(this.offset, this.limit()); - if (nameOrPath instanceof BasePath) { - nameOrPath.forEach(segment => { - segments.push(segment); - }); - } - else { - segments.push(nameOrPath); - } - return this.construct(segments); - } - /** The index of one past the last segment of the path. */ - limit() { - return this.offset + this.length; - } - popFirst(size) { - size = size === undefined ? 1 : size; - return this.construct(this.segments, this.offset + size, this.length - size); - } - popLast() { - return this.construct(this.segments, this.offset, this.length - 1); - } - firstSegment() { - return this.segments[this.offset]; - } - lastSegment() { - return this.get(this.length - 1); - } - get(index) { - return this.segments[this.offset + index]; - } - isEmpty() { - return this.length === 0; - } - isPrefixOf(other) { - if (other.length < this.length) { - return false; - } - for (let i = 0; i < this.length; i++) { - if (this.get(i) !== other.get(i)) { - return false; - } - } - return true; - } - isImmediateParentOf(potentialChild) { - if (this.length + 1 !== potentialChild.length) { - return false; - } - for (let i = 0; i < this.length; i++) { - if (this.get(i) !== potentialChild.get(i)) { - return false; - } - } - return true; - } - forEach(fn) { - for (let i = this.offset, end = this.limit(); i < end; i++) { - fn(this.segments[i]); - } - } - toArray() { - return this.segments.slice(this.offset, this.limit()); - } - static comparator(p1, p2) { - const len = Math.min(p1.length, p2.length); - for (let i = 0; i < len; i++) { - const left = p1.get(i); - const right = p2.get(i); - if (left < right) { - return -1; - } - if (left > right) { - return 1; - } - } - if (p1.length < p2.length) { - return -1; - } - if (p1.length > p2.length) { - return 1; - } - return 0; - } - } - /** - * A slash-separated path for navigating resources (documents and collections) - * within Firestore. - * - * @internal - */ - class ResourcePath extends BasePath { - construct(segments, offset, length) { - return new ResourcePath(segments, offset, length); - } - canonicalString() { - // NOTE: The client is ignorant of any path segments containing escape - // sequences (e.g. __id123__) and just passes them through raw (they exist - // for legacy reasons and should not be used frequently). - return this.toArray().join('/'); - } - toString() { - return this.canonicalString(); - } - /** - * Returns a string representation of this path - * where each path segment has been encoded with - * `encodeURIComponent`. - */ - toUriEncodedString() { - return this.toArray().map(encodeURIComponent).join('/'); - } - /** - * Creates a resource path from the given slash-delimited string. If multiple - * arguments are provided, all components are combined. Leading and trailing - * slashes from all components are ignored. - */ - static fromString(...pathComponents) { - // NOTE: The client is ignorant of any path segments containing escape - // sequences (e.g. __id123__) and just passes them through raw (they exist - // for legacy reasons and should not be used frequently). - const segments = []; - for (const path of pathComponents) { - if (path.indexOf('//') >= 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); - } - // Strip leading and trailing slashed. - segments.push(...path.split('/').filter(segment => segment.length > 0)); - } - return new ResourcePath(segments); - } - static emptyPath() { - return new ResourcePath([]); - } - } - const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; - /** - * A dot-separated path for navigating sub-objects within a document. - * @internal - */ - class FieldPath$1 extends BasePath { - construct(segments, offset, length) { - return new FieldPath$1(segments, offset, length); - } - /** - * Returns true if the string could be used as a segment in a field path - * without escaping. - */ - static isValidIdentifier(segment) { - return identifierRegExp.test(segment); - } - canonicalString() { - return this.toArray() - .map(str => { - str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); - if (!FieldPath$1.isValidIdentifier(str)) { - str = '`' + str + '`'; - } - return str; - }) - .join('.'); - } - toString() { - return this.canonicalString(); - } - /** - * Returns true if this field references the key of a document. - */ - isKeyField() { - return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; - } - /** - * The field designating the key of a document. - */ - static keyField() { - return new FieldPath$1([DOCUMENT_KEY_NAME]); - } - /** - * Parses a field string from the given server-formatted string. - * - * - Splitting the empty string is not allowed (for now at least). - * - Empty segments within the string (e.g. if there are two consecutive - * separators) are not allowed. - * - * TODO(b/37244157): we should make this more strict. Right now, it allows - * non-identifier path components, even if they aren't escaped. - */ - static fromServerFormat(path) { - const segments = []; - let current = ''; - let i = 0; - const addCurrentSegment = () => { - if (current.length === 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + - `with '.', end with '.', or contain '..'`); - } - segments.push(current); - current = ''; - }; - let inBackticks = false; - while (i < path.length) { - const c = path[i]; - if (c === '\\') { - if (i + 1 === path.length) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); - } - const next = path[i + 1]; - if (!(next === '\\' || next === '.' || next === '`')) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); - } - current += next; - i += 2; - } - else if (c === '`') { - inBackticks = !inBackticks; - i++; - } - else if (c === '.' && !inBackticks) { - addCurrentSegment(); - i++; - } - else { - current += c; - i++; - } - } - addCurrentSegment(); - if (inBackticks) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); - } - return new FieldPath$1(segments); - } - static emptyPath() { - return new FieldPath$1([]); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * @internal - */ - class DocumentKey { - constructor(path) { - this.path = path; - } - static fromPath(path) { - return new DocumentKey(ResourcePath.fromString(path)); - } - static fromName(name) { - return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); - } - static empty() { - return new DocumentKey(ResourcePath.emptyPath()); - } - get collectionGroup() { - return this.path.popLast().lastSegment(); - } - /** Returns true if the document is in the specified collectionId. */ - hasCollectionId(collectionId) { - return (this.path.length >= 2 && - this.path.get(this.path.length - 2) === collectionId); - } - /** Returns the collection group (i.e. the name of the parent collection) for this key. */ - getCollectionGroup() { - return this.path.get(this.path.length - 2); - } - /** Returns the fully qualified path to the parent collection. */ - getCollectionPath() { - return this.path.popLast(); - } - isEqual(other) { - return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); - } - toString() { - return this.path.toString(); - } - static comparator(k1, k2) { - return ResourcePath.comparator(k1.path, k2.path); - } - static isDocumentKey(path) { - return path.length % 2 === 0; - } - /** - * Creates and returns a new document key with the given segments. - * - * @param segments - The segments of the path to the document - * @returns A new instance of DocumentKey - */ - static fromSegments(segments) { - return new DocumentKey(new ResourcePath(segments.slice())); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - function validateNonEmptyArgument(functionName, argumentName, argument) { - if (!argument) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); - } - } - /** - * Validates that two boolean options are not set at the same time. - * @internal - */ - function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { - if (argument1 === true && argument2 === true) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); - } - } - /** - * Validates that `path` refers to a document (indicated by the fact it contains - * an even numbers of segments). - */ - function validateDocumentPath(path) { - if (!DocumentKey.isDocumentKey(path)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); - } - } - /** - * Validates that `path` refers to a collection (indicated by the fact it - * contains an odd numbers of segments). - */ - function validateCollectionPath(path) { - if (DocumentKey.isDocumentKey(path)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); - } - } - /** - * Returns true if it's a non-null object without a custom prototype - * (i.e. excludes Array, Date, etc.). - */ - function isPlainObject(input) { - return (typeof input === 'object' && - input !== null && - (Object.getPrototypeOf(input) === Object.prototype || - Object.getPrototypeOf(input) === null)); - } - /** Returns a string describing the type / value of the provided input. */ - function valueDescription(input) { - if (input === undefined) { - return 'undefined'; - } - else if (input === null) { - return 'null'; - } - else if (typeof input === 'string') { - if (input.length > 20) { - input = `${input.substring(0, 20)}...`; - } - return JSON.stringify(input); - } - else if (typeof input === 'number' || typeof input === 'boolean') { - return '' + input; - } - else if (typeof input === 'object') { - if (input instanceof Array) { - return 'an array'; - } - else { - const customObjectName = tryGetCustomObjectType(input); - if (customObjectName) { - return `a custom ${customObjectName} object`; - } - else { - return 'an object'; - } - } - } - else if (typeof input === 'function') { - return 'a function'; - } - else { - return fail(); - } - } - /** try to get the constructor name for an object. */ - function tryGetCustomObjectType(input) { - if (input.constructor) { - return input.constructor.name; - } - return null; - } - /** - * Casts `obj` to `T`, optionally unwrapping Compat types to expose the - * underlying instance. Throws if `obj` is not an instance of `T`. - * - * This cast is used in the Lite and Full SDK to verify instance types for - * arguments passed to the public API. - * @internal - */ - function cast(obj, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor) { - if ('_delegate' in obj) { - // Unwrap Compat types - // eslint-disable-next-line @typescript-eslint/no-explicit-any - obj = obj._delegate; - } - if (!(obj instanceof constructor)) { - if (constructor.name === obj.constructor.name) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + - `reference from a different Firestore SDK?`); - } - else { - const description = valueDescription(obj); - throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); - } - } - return obj; - } - function validatePositiveNumber(functionName, n) { - if (n <= 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); - } - } - - /** - * @license - * Copyright 2023 Google LLC - * - * 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. - */ - /** - * Compares two `ExperimentalLongPollingOptions` objects for equality. - */ - function longPollingOptionsEqual(options1, options2) { - return options1.timeoutSeconds === options2.timeoutSeconds; - } - /** - * Creates and returns a new `ExperimentalLongPollingOptions` with the same - * option values as the given instance. - */ - function cloneLongPollingOptions(options) { - const clone = {}; - if (options.timeoutSeconds !== undefined) { - clone.timeoutSeconds = options.timeoutSeconds; - } - return clone; - } - - /** - * @license - * Copyright 2023 Google LLC - * - * 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. - */ - /** - * The value returned from the most recent invocation of - * `generateUniqueDebugId()`, or null if it has never been invoked. - */ - let lastUniqueDebugId = null; - /** - * Generates and returns an initial value for `lastUniqueDebugId`. - * - * The returned value is randomly selected from a range of integers that are - * represented as 8 hexadecimal digits. This means that (within reason) any - * numbers generated by incrementing the returned number by 1 will also be - * represented by 8 hexadecimal digits. This leads to all "IDs" having the same - * length when converted to a hexadecimal string, making reading logs containing - * these IDs easier to follow. And since the return value is randomly selected - * it will help to differentiate between logs from different executions. - */ - function generateInitialUniqueDebugId() { - const minResult = 0x10000000; - const maxResult = 0x90000000; - const resultRange = maxResult - minResult; - const resultOffset = Math.round(resultRange * Math.random()); - return minResult + resultOffset; - } - /** - * Generates and returns a unique ID as a hexadecimal string. - * - * The returned ID is intended to be used in debug logging messages to help - * correlate log messages that may be spatially separated in the logs, but - * logically related. For example, a network connection could include the same - * "debug ID" string in all of its log messages to help trace a specific - * connection over time. - * - * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). - */ - function generateUniqueDebugId() { - if (lastUniqueDebugId === null) { - lastUniqueDebugId = generateInitialUniqueDebugId(); - } - else { - lastUniqueDebugId++; - } - return '0x' + lastUniqueDebugId.toString(16); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - const LOG_TAG$3 = 'RestConnection'; - /** - * Maps RPC names to the corresponding REST endpoint name. - * - * We use array notation to avoid mangling. - */ - const RPC_NAME_URL_MAPPING = {}; - RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet'; - RPC_NAME_URL_MAPPING['Commit'] = 'commit'; - RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery'; - RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery'; - const RPC_URL_VERSION = 'v1'; - // SDK_VERSION is updated to different value at runtime depending on the entry point, - // so we need to get its value when we need it in a function. - function getGoogApiClientValue() { - return 'gl-js/ fire/' + SDK_VERSION; - } - /** - * Base class for all Rest-based connections to the backend (WebChannel and - * HTTP). - */ - class RestConnection { - constructor(databaseInfo) { - this.databaseInfo = databaseInfo; - this.databaseId = databaseInfo.databaseId; - const proto = databaseInfo.ssl ? 'https' : 'http'; - const projectId = encodeURIComponent(this.databaseId.projectId); - const databaseId = encodeURIComponent(this.databaseId.database); - this.baseUrl = proto + '://' + databaseInfo.host; - this.databasePath = `projects/${projectId}/databases/${databaseId}`; - this.requestParams = - this.databaseId.database === DEFAULT_DATABASE_NAME - ? `project_id=${projectId}` - : `project_id=${projectId}&database_id=${databaseId}`; - } - get shouldResourcePathBeIncludedInRequest() { - // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine - // where to run the query, and expect the `request` to NOT specify the "path". - return false; - } - invokeRPC(rpcName, path, req, authToken, appCheckToken) { - const streamId = generateUniqueDebugId(); - const url = this.makeUrl(rpcName, path.toUriEncodedString()); - logDebug(LOG_TAG$3, `Sending RPC '${rpcName}' ${streamId}:`, url, req); - const headers = { - 'google-cloud-resource-prefix': this.databasePath, - 'x-goog-request-params': this.requestParams - }; - this.modifyHeadersForRequest(headers, authToken, appCheckToken); - return this.performRPCRequest(rpcName, url, headers, req).then(response => { - logDebug(LOG_TAG$3, `Received RPC '${rpcName}' ${streamId}: `, response); - return response; - }, (err) => { - logWarn(LOG_TAG$3, `RPC '${rpcName}' ${streamId} failed with error: `, err, 'url: ', url, 'request:', req); - throw err; - }); - } - invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { - // The REST API automatically aggregates all of the streamed results, so we - // can just use the normal invoke() method. - return this.invokeRPC(rpcName, path, request, authToken, appCheckToken); - } - /** - * Modifies the headers for a request, adding any authorization token if - * present and any additional headers for the request. - */ - modifyHeadersForRequest(headers, authToken, appCheckToken) { - headers['X-Goog-Api-Client'] = getGoogApiClientValue(); - // Content-Type: text/plain will avoid preflight requests which might - // mess with CORS and redirects by proxies. If we add custom headers - // we will need to change this code to potentially use the $httpOverwrite - // parameter supported by ESF to avoid triggering preflight requests. - headers['Content-Type'] = 'text/plain'; - if (this.databaseInfo.appId) { - headers['X-Firebase-GMPID'] = this.databaseInfo.appId; - } - if (authToken) { - authToken.headers.forEach((value, key) => (headers[key] = value)); - } - if (appCheckToken) { - appCheckToken.headers.forEach((value, key) => (headers[key] = value)); - } - } - makeUrl(rpcName, path) { - const urlRpcName = RPC_NAME_URL_MAPPING[rpcName]; - return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`; - } - /** - * Closes and cleans up any resources associated with the connection. This - * implementation is a no-op because there are no resources associated - * with the RestConnection that need to be cleaned up. - */ - terminate() { - // No-op - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Error Codes describing the different ways GRPC can fail. These are copied - * directly from GRPC's sources here: - * - * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h - * - * Important! The names of these identifiers matter because the string forms - * are used for reverse lookups from the webchannel stream. Do NOT change the - * names of these identifiers or change this into a const enum. - */ - var RpcCode; - (function (RpcCode) { - RpcCode[RpcCode["OK"] = 0] = "OK"; - RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; - RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; - RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; - RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; - RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; - RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; - RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; - RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; - RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; - RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; - RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; - RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; - RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; - RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; - RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; - RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; - })(RpcCode || (RpcCode = {})); - /** - * Determines whether an error code represents a permanent error when received - * in response to a non-write operation. - * - * See isPermanentWriteError for classifying write errors. - */ - function isPermanentError(code) { - switch (code) { - case Code.OK: - return fail(); - case Code.CANCELLED: - case Code.UNKNOWN: - case Code.DEADLINE_EXCEEDED: - case Code.RESOURCE_EXHAUSTED: - case Code.INTERNAL: - case Code.UNAVAILABLE: - // Unauthenticated means something went wrong with our token and we need - // to retry with new credentials which will happen automatically. - case Code.UNAUTHENTICATED: - return false; - case Code.INVALID_ARGUMENT: - case Code.NOT_FOUND: - case Code.ALREADY_EXISTS: - case Code.PERMISSION_DENIED: - case Code.FAILED_PRECONDITION: - // Aborted might be retried in some scenarios, but that is dependent on - // the context and should handled individually by the calling code. - // See https://cloud.google.com/apis/design/errors. - case Code.ABORTED: - case Code.OUT_OF_RANGE: - case Code.UNIMPLEMENTED: - case Code.DATA_LOSS: - return true; - default: - return fail(); - } - } - /** - * Converts an HTTP Status Code to the equivalent error code. - * - * @param status - An HTTP Status Code, like 200, 404, 503, etc. - * @returns The equivalent Code. Unknown status codes are mapped to - * Code.UNKNOWN. - */ - function mapCodeFromHttpStatus(status) { - if (status === undefined) { - logError('RPC_ERROR', 'HTTP error has no status'); - return Code.UNKNOWN; - } - // The canonical error codes for Google APIs [1] specify mapping onto HTTP - // status codes but the mapping is not bijective. In each case of ambiguity - // this function chooses a primary error. - // - // [1] - // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto - switch (status) { - case 200: // OK - return Code.OK; - case 400: // Bad Request - return Code.FAILED_PRECONDITION; - // Other possibilities based on the forward mapping - // return Code.INVALID_ARGUMENT; - // return Code.OUT_OF_RANGE; - case 401: // Unauthorized - return Code.UNAUTHENTICATED; - case 403: // Forbidden - return Code.PERMISSION_DENIED; - case 404: // Not Found - return Code.NOT_FOUND; - case 409: // Conflict - return Code.ABORTED; - // Other possibilities: - // return Code.ALREADY_EXISTS; - case 416: // Range Not Satisfiable - return Code.OUT_OF_RANGE; - case 429: // Too Many Requests - return Code.RESOURCE_EXHAUSTED; - case 499: // Client Closed Request - return Code.CANCELLED; - case 500: // Internal Server Error - return Code.UNKNOWN; - // Other possibilities: - // return Code.INTERNAL; - // return Code.DATA_LOSS; - case 501: // Unimplemented - return Code.UNIMPLEMENTED; - case 503: // Service Unavailable - return Code.UNAVAILABLE; - case 504: // Gateway Timeout - return Code.DEADLINE_EXCEEDED; - default: - if (status >= 200 && status < 300) { - return Code.OK; - } - if (status >= 400 && status < 500) { - return Code.FAILED_PRECONDITION; - } - if (status >= 500 && status < 600) { - return Code.INTERNAL; - } - return Code.UNKNOWN; - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * A Rest-based connection that relies on the native HTTP stack - * (e.g. `fetch` or a polyfill). - */ - class FetchConnection extends RestConnection { - openStream(rpcName, token) { - throw new Error('Not supported by FetchConnection'); - } - async performRPCRequest(rpcName, url, headers, body) { - var _a; - const requestJson = JSON.stringify(body); - let response; - try { - response = await fetch(url, { - method: 'POST', - headers, - body: requestJson - }); - } - catch (e) { - const err = e; - throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText); - } - if (!response.ok) { - let errorResponse = await response.json(); - if (Array.isArray(errorResponse)) { - errorResponse = errorResponse[0]; - } - const errorMessage = (_a = errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.error) === null || _a === void 0 ? void 0 : _a.message; - throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage !== null && errorMessage !== void 0 ? errorMessage : response.statusText}`); - } - return response.json(); - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** Initializes the HTTP connection for the REST API. */ - function newConnection(databaseInfo) { - return new FetchConnection(databaseInfo); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Generates `nBytes` of random bytes. - * - * If `nBytes < 0` , an error will be thrown. - */ - function randomBytes(nBytes) { - return crypto.randomBytes(nBytes); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * A utility class for generating unique alphanumeric IDs of a specified length. - * - * @internal - * Exported internally for testing purposes. - */ - class AutoId { - static newId() { - // Alphanumeric characters - const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - // The largest byte value that is a multiple of `char.length`. - const maxMultiple = Math.floor(256 / chars.length) * chars.length; - let autoId = ''; - const targetLength = 20; - while (autoId.length < targetLength) { - const bytes = randomBytes(40); - for (let i = 0; i < bytes.length; ++i) { - // Only accept values that are [0, maxMultiple), this ensures they can - // be evenly mapped to indices of `chars` via a modulo operation. - if (autoId.length < targetLength && bytes[i] < maxMultiple) { - autoId += chars.charAt(bytes[i] % chars.length); - } - } - } - return autoId; - } - } - function primitiveComparator(left, right) { - if (left < right) { - return -1; - } - if (left > right) { - return 1; - } - return 0; - } - /** Helper to compare arrays using isEqual(). */ - function arrayEquals(left, right, comparator) { - if (left.length !== right.length) { - return false; - } - return left.every((value, index) => comparator(value, right[index])); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - function objectSize(obj) { - let count = 0; - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - count++; - } - } - return count; - } - function forEach(obj, fn) { - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn(key, obj[key]); - } - } - } - function mapToArray(obj, fn) { - const result = []; - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - result.push(fn(obj[key], key, obj)); - } - } - return result; - } - function isEmpty(obj) { - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - return false; - } - } - return true; - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Returns whether a variable is either undefined or null. - */ - function isNullOrUndefined(value) { - return value === null || value === undefined; - } - /** Returns whether the value represents -0. */ - function isNegativeZero(value) { - // Detect if the value is -0.0. Based on polyfill from - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - return value === 0 && 1 / value === 1 / -0; - } - /** - * Returns whether a value is an integer and in the safe integer range - * @param value - The value to test for being an integer and in the safe range - */ - function isSafeInteger(value) { - return (typeof value === 'number' && - Number.isInteger(value) && - !isNegativeZero(value) && - value <= Number.MAX_SAFE_INTEGER && - value >= Number.MIN_SAFE_INTEGER); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** Converts a Base64 encoded string to a binary string. */ - function decodeBase64(encoded) { - // Note: We used to validate the base64 string here via a regular expression. - // This was removed to improve the performance of indexing. - return Buffer.from(encoded, 'base64').toString('binary'); - } - /** Converts a binary string to a Base64 encoded string. */ - function encodeBase64(raw) { - return Buffer.from(raw, 'binary').toString('base64'); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Immutable class that represents a "proto" byte string. - * - * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when - * sent on the wire. This class abstracts away this differentiation by holding - * the proto byte string in a common class that must be converted into a string - * before being sent as a proto. - * @internal - */ - class ByteString { - constructor(binaryString) { - this.binaryString = binaryString; - } - static fromBase64String(base64) { - const binaryString = decodeBase64(base64); - return new ByteString(binaryString); - } - static fromUint8Array(array) { - // TODO(indexing); Remove the copy of the byte string here as this method - // is frequently called during indexing. - const binaryString = binaryStringFromUint8Array(array); - return new ByteString(binaryString); - } - [Symbol.iterator]() { - let i = 0; - return { - next: () => { - if (i < this.binaryString.length) { - return { value: this.binaryString.charCodeAt(i++), done: false }; - } - else { - return { value: undefined, done: true }; - } - } - }; - } - toBase64() { - return encodeBase64(this.binaryString); - } - toUint8Array() { - return uint8ArrayFromBinaryString(this.binaryString); - } - approximateByteSize() { - return this.binaryString.length * 2; - } - compareTo(other) { - return primitiveComparator(this.binaryString, other.binaryString); - } - isEqual(other) { - return this.binaryString === other.binaryString; - } - } - ByteString.EMPTY_BYTE_STRING = new ByteString(''); - /** - * Helper function to convert an Uint8array to a binary string. - */ - function binaryStringFromUint8Array(array) { - let binaryString = ''; - for (let i = 0; i < array.length; ++i) { - binaryString += String.fromCharCode(array[i]); - } - return binaryString; - } - /** - * Helper function to convert a binary string to an Uint8Array. - */ - function uint8ArrayFromBinaryString(binaryString) { - const buffer = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - buffer[i] = binaryString.charCodeAt(i); - } - return buffer; - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - // A RegExp matching ISO 8601 UTC timestamps with optional fraction. - const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); - /** - * Converts the possible Proto values for a timestamp value into a "seconds and - * nanos" representation. - */ - function normalizeTimestamp(date) { - hardAssert(!!date); - // The json interface (for the browser) will return an iso timestamp string, - // while the proto js library (for node) will return a - // google.protobuf.Timestamp instance. - if (typeof date === 'string') { - // The date string can have higher precision (nanos) than the Date class - // (millis), so we do some custom parsing here. - // Parse the nanos right out of the string. - let nanos = 0; - const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); - hardAssert(!!fraction); - if (fraction[1]) { - // Pad the fraction out to 9 digits (nanos). - let nanoStr = fraction[1]; - nanoStr = (nanoStr + '000000000').substr(0, 9); - nanos = Number(nanoStr); - } - // Parse the date to get the seconds. - const parsedDate = new Date(date); - const seconds = Math.floor(parsedDate.getTime() / 1000); - return { seconds, nanos }; - } - else { - // TODO(b/37282237): Use strings for Proto3 timestamps - // assert(!this.options.useProto3Json, - // 'The timestamp instance format requires Proto JS.'); - const seconds = normalizeNumber(date.seconds); - const nanos = normalizeNumber(date.nanos); - return { seconds, nanos }; - } - } - /** - * Converts the possible Proto types for numbers into a JavaScript number. - * Returns 0 if the value is not numeric. - */ - function normalizeNumber(value) { - // TODO(bjornick): Handle int64 greater than 53 bits. - if (typeof value === 'number') { - return value; - } - else if (typeof value === 'string') { - return Number(value); - } - else { - return 0; - } - } - /** Converts the possible Proto types for Blobs into a ByteString. */ - function normalizeByteString(blob) { - if (typeof blob === 'string') { - return ByteString.fromBase64String(blob); - } - else { - return ByteString.fromUint8Array(blob); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). - const MIN_SECONDS = -62135596800; - // Number of nanoseconds in a millisecond. - const MS_TO_NANOS = 1e6; - /** - * A `Timestamp` represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. - * - * It is encoded using the Proleptic Gregorian Calendar which extends the - * Gregorian calendar backwards to year one. It is encoded assuming all minutes - * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59.999999999Z. - * - * For examples and further specifications, refer to the - * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. - */ - class Timestamp { - /** - * Creates a new timestamp. - * - * @param seconds - The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * @param nanoseconds - The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive. - */ - constructor( - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - seconds, - /** - * The fractions of a second at nanosecond resolution.* - */ - nanoseconds) { - this.seconds = seconds; - this.nanoseconds = nanoseconds; - if (nanoseconds < 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); - } - if (nanoseconds >= 1e9) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); - } - if (seconds < MIN_SECONDS) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); - } - // This will break in the year 10,000. - if (seconds >= 253402300800) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); - } - } - /** - * Creates a new timestamp with the current date, with millisecond precision. - * - * @returns a new timestamp representing the current date. - */ - static now() { - return Timestamp.fromMillis(Date.now()); - } - /** - * Creates a new timestamp from the given date. - * - * @param date - The date to initialize the `Timestamp` from. - * @returns A new `Timestamp` representing the same point in time as the given - * date. - */ - static fromDate(date) { - return Timestamp.fromMillis(date.getTime()); - } - /** - * Creates a new timestamp from the given number of milliseconds. - * - * @param milliseconds - Number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - * @returns A new `Timestamp` representing the same point in time as the given - * number of milliseconds. - */ - static fromMillis(milliseconds) { - const seconds = Math.floor(milliseconds / 1000); - const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); - return new Timestamp(seconds, nanos); - } - /** - * Converts a `Timestamp` to a JavaScript `Date` object. This conversion - * causes a loss of precision since `Date` objects only support millisecond - * precision. - * - * @returns JavaScript `Date` object representing the same point in time as - * this `Timestamp`, with millisecond precision. - */ - toDate() { - return new Date(this.toMillis()); - } - /** - * Converts a `Timestamp` to a numeric timestamp (in milliseconds since - * epoch). This operation causes a loss of precision. - * - * @returns The point in time corresponding to this timestamp, represented as - * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - */ - toMillis() { - return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; - } - _compareTo(other) { - if (this.seconds === other.seconds) { - return primitiveComparator(this.nanoseconds, other.nanoseconds); - } - return primitiveComparator(this.seconds, other.seconds); - } - /** - * Returns true if this `Timestamp` is equal to the provided one. - * - * @param other - The `Timestamp` to compare against. - * @returns true if this `Timestamp` is equal to the provided one. - */ - isEqual(other) { - return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); - } - /** Returns a textual representation of this `Timestamp`. */ - toString() { - return ('Timestamp(seconds=' + - this.seconds + - ', nanoseconds=' + - this.nanoseconds + - ')'); - } - /** Returns a JSON-serializable representation of this `Timestamp`. */ - toJSON() { - return { seconds: this.seconds, nanoseconds: this.nanoseconds }; - } - /** - * Converts this object to a primitive string, which allows `Timestamp` objects - * to be compared using the `>`, `<=`, `>=` and `>` operators. - */ - valueOf() { - // This method returns a string of the form . where - // is translated to have a non-negative value and both - // and are left-padded with zeroes to be a consistent length. - // Strings with this format then have a lexicographical ordering that matches - // the expected ordering. The translation is done to avoid having - // a leading negative sign (i.e. a leading '-' character) in its string - // representation, which would affect its lexicographical ordering. - const adjustedSeconds = this.seconds - MIN_SECONDS; - // Note: Up to 12 decimal digits are required to represent all valid - // 'seconds' values. - const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); - const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); - return formattedSeconds + '.' + formattedNanoseconds; - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Represents a locally-applied ServerTimestamp. - * - * Server Timestamps are backed by MapValues that contain an internal field - * `__type__` with a value of `server_timestamp`. The previous value and local - * write time are stored in its `__previous_value__` and `__local_write_time__` - * fields respectively. - * - * Notes: - * - ServerTimestampValue instances are created as the result of applying a - * transform. They can only exist in the local view of a document. Therefore - * they do not need to be parsed or serialized. - * - When evaluated locally (e.g. for snapshot.data()), they by default - * evaluate to `null`. This behavior can be configured by passing custom - * FieldValueOptions to value(). - * - With respect to other ServerTimestampValues, they sort by their - * localWriteTime. - */ - const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; - const TYPE_KEY$1 = '__type__'; - const PREVIOUS_VALUE_KEY = '__previous_value__'; - const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; - function isServerTimestamp(value) { - var _a, _b; - const type = (_b = (((_a = value === null || value === void 0 ? void 0 : value.mapValue) === null || _a === void 0 ? void 0 : _a.fields) || {})[TYPE_KEY$1]) === null || _b === void 0 ? void 0 : _b.stringValue; - return type === SERVER_TIMESTAMP_SENTINEL; - } - /** - * Returns the value of the field before this ServerTimestamp was set. - * - * Preserving the previous values allows the user to display the last resoled - * value until the backend responds with the timestamp. - */ - function getPreviousValue(value) { - const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; - if (isServerTimestamp(previousValue)) { - return getPreviousValue(previousValue); - } - return previousValue; - } - /** - * Returns the local time at which this timestamp was first set. - */ - function getLocalWriteTime(value) { - const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); - return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - const TYPE_KEY = '__type__'; - const MAX_VALUE_TYPE = '__max__'; - const MAX_VALUE = { - mapValue: { - fields: { - '__type__': { stringValue: MAX_VALUE_TYPE } - } - } - }; - const VECTOR_VALUE_SENTINEL = '__vector__'; - const VECTOR_MAP_VECTORS_KEY = 'value'; - /** Extracts the backend's type order for the provided value. */ - function typeOrder(value) { - if ('nullValue' in value) { - return 0 /* TypeOrder.NullValue */; - } - else if ('booleanValue' in value) { - return 1 /* TypeOrder.BooleanValue */; - } - else if ('integerValue' in value || 'doubleValue' in value) { - return 2 /* TypeOrder.NumberValue */; - } - else if ('timestampValue' in value) { - return 3 /* TypeOrder.TimestampValue */; - } - else if ('stringValue' in value) { - return 5 /* TypeOrder.StringValue */; - } - else if ('bytesValue' in value) { - return 6 /* TypeOrder.BlobValue */; - } - else if ('referenceValue' in value) { - return 7 /* TypeOrder.RefValue */; - } - else if ('geoPointValue' in value) { - return 8 /* TypeOrder.GeoPointValue */; - } - else if ('arrayValue' in value) { - return 9 /* TypeOrder.ArrayValue */; - } - else if ('mapValue' in value) { - if (isServerTimestamp(value)) { - return 4 /* TypeOrder.ServerTimestampValue */; - } - else if (isMaxValue(value)) { - return 9007199254740991 /* TypeOrder.MaxValue */; - } - else if (isVectorValue(value)) { - return 10 /* TypeOrder.VectorValue */; - } - return 11 /* TypeOrder.ObjectValue */; - } - else { - return fail(); - } - } - /** Tests `left` and `right` for equality based on the backend semantics. */ - function valueEquals(left, right) { - if (left === right) { - return true; - } - const leftType = typeOrder(left); - const rightType = typeOrder(right); - if (leftType !== rightType) { - return false; - } - switch (leftType) { - case 0 /* TypeOrder.NullValue */: - return true; - case 1 /* TypeOrder.BooleanValue */: - return left.booleanValue === right.booleanValue; - case 4 /* TypeOrder.ServerTimestampValue */: - return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); - case 3 /* TypeOrder.TimestampValue */: - return timestampEquals(left, right); - case 5 /* TypeOrder.StringValue */: - return left.stringValue === right.stringValue; - case 6 /* TypeOrder.BlobValue */: - return blobEquals(left, right); - case 7 /* TypeOrder.RefValue */: - return left.referenceValue === right.referenceValue; - case 8 /* TypeOrder.GeoPointValue */: - return geoPointEquals(left, right); - case 2 /* TypeOrder.NumberValue */: - return numberEquals(left, right); - case 9 /* TypeOrder.ArrayValue */: - return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); - case 10 /* TypeOrder.VectorValue */: - case 11 /* TypeOrder.ObjectValue */: - return objectEquals(left, right); - case 9007199254740991 /* TypeOrder.MaxValue */: - return true; - default: - return fail(); - } - } - function timestampEquals(left, right) { - if (typeof left.timestampValue === 'string' && - typeof right.timestampValue === 'string' && - left.timestampValue.length === right.timestampValue.length) { - // Use string equality for ISO 8601 timestamps - return left.timestampValue === right.timestampValue; - } - const leftTimestamp = normalizeTimestamp(left.timestampValue); - const rightTimestamp = normalizeTimestamp(right.timestampValue); - return (leftTimestamp.seconds === rightTimestamp.seconds && - leftTimestamp.nanos === rightTimestamp.nanos); - } - function geoPointEquals(left, right) { - return (normalizeNumber(left.geoPointValue.latitude) === - normalizeNumber(right.geoPointValue.latitude) && - normalizeNumber(left.geoPointValue.longitude) === - normalizeNumber(right.geoPointValue.longitude)); - } - function blobEquals(left, right) { - return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); - } - function numberEquals(left, right) { - if ('integerValue' in left && 'integerValue' in right) { - return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); - } - else if ('doubleValue' in left && 'doubleValue' in right) { - const n1 = normalizeNumber(left.doubleValue); - const n2 = normalizeNumber(right.doubleValue); - if (n1 === n2) { - return isNegativeZero(n1) === isNegativeZero(n2); - } - else { - return isNaN(n1) && isNaN(n2); - } - } - return false; - } - function objectEquals(left, right) { - const leftMap = left.mapValue.fields || {}; - const rightMap = right.mapValue.fields || {}; - if (objectSize(leftMap) !== objectSize(rightMap)) { - return false; - } - for (const key in leftMap) { - if (leftMap.hasOwnProperty(key)) { - if (rightMap[key] === undefined || - !valueEquals(leftMap[key], rightMap[key])) { - return false; - } - } - } - return true; - } - /** Returns true if the ArrayValue contains the specified element. */ - function arrayValueContains(haystack, needle) { - return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); - } - function valueCompare(left, right) { - if (left === right) { - return 0; - } - const leftType = typeOrder(left); - const rightType = typeOrder(right); - if (leftType !== rightType) { - return primitiveComparator(leftType, rightType); - } - switch (leftType) { - case 0 /* TypeOrder.NullValue */: - case 9007199254740991 /* TypeOrder.MaxValue */: - return 0; - case 1 /* TypeOrder.BooleanValue */: - return primitiveComparator(left.booleanValue, right.booleanValue); - case 2 /* TypeOrder.NumberValue */: - return compareNumbers(left, right); - case 3 /* TypeOrder.TimestampValue */: - return compareTimestamps(left.timestampValue, right.timestampValue); - case 4 /* TypeOrder.ServerTimestampValue */: - return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); - case 5 /* TypeOrder.StringValue */: - return primitiveComparator(left.stringValue, right.stringValue); - case 6 /* TypeOrder.BlobValue */: - return compareBlobs(left.bytesValue, right.bytesValue); - case 7 /* TypeOrder.RefValue */: - return compareReferences(left.referenceValue, right.referenceValue); - case 8 /* TypeOrder.GeoPointValue */: - return compareGeoPoints(left.geoPointValue, right.geoPointValue); - case 9 /* TypeOrder.ArrayValue */: - return compareArrays(left.arrayValue, right.arrayValue); - case 10 /* TypeOrder.VectorValue */: - return compareVectors(left.mapValue, right.mapValue); - case 11 /* TypeOrder.ObjectValue */: - return compareMaps(left.mapValue, right.mapValue); - default: - throw fail(); - } - } - function compareNumbers(left, right) { - const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); - const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); - if (leftNumber < rightNumber) { - return -1; - } - else if (leftNumber > rightNumber) { - return 1; - } - else if (leftNumber === rightNumber) { - return 0; - } - else { - // one or both are NaN. - if (isNaN(leftNumber)) { - return isNaN(rightNumber) ? 0 : -1; - } - else { - return 1; - } - } - } - function compareTimestamps(left, right) { - if (typeof left === 'string' && - typeof right === 'string' && - left.length === right.length) { - return primitiveComparator(left, right); - } - const leftTimestamp = normalizeTimestamp(left); - const rightTimestamp = normalizeTimestamp(right); - const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); - if (comparison !== 0) { - return comparison; - } - return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); - } - function compareReferences(leftPath, rightPath) { - const leftSegments = leftPath.split('/'); - const rightSegments = rightPath.split('/'); - for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { - const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); - if (comparison !== 0) { - return comparison; - } - } - return primitiveComparator(leftSegments.length, rightSegments.length); - } - function compareGeoPoints(left, right) { - const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); - if (comparison !== 0) { - return comparison; - } - return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); - } - function compareBlobs(left, right) { - const leftBytes = normalizeByteString(left); - const rightBytes = normalizeByteString(right); - return leftBytes.compareTo(rightBytes); - } - function compareArrays(left, right) { - const leftArray = left.values || []; - const rightArray = right.values || []; - for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { - const compare = valueCompare(leftArray[i], rightArray[i]); - if (compare) { - return compare; - } - } - return primitiveComparator(leftArray.length, rightArray.length); - } - function compareVectors(left, right) { - var _a, _b, _c, _d; - const leftMap = left.fields || {}; - const rightMap = right.fields || {}; - // The vector is a map, but only vector value is compared. - const leftArrayValue = (_a = leftMap[VECTOR_MAP_VECTORS_KEY]) === null || _a === void 0 ? void 0 : _a.arrayValue; - const rightArrayValue = (_b = rightMap[VECTOR_MAP_VECTORS_KEY]) === null || _b === void 0 ? void 0 : _b.arrayValue; - const lengthCompare = primitiveComparator(((_c = leftArrayValue === null || leftArrayValue === void 0 ? void 0 : leftArrayValue.values) === null || _c === void 0 ? void 0 : _c.length) || 0, ((_d = rightArrayValue === null || rightArrayValue === void 0 ? void 0 : rightArrayValue.values) === null || _d === void 0 ? void 0 : _d.length) || 0); - if (lengthCompare !== 0) { - return lengthCompare; - } - return compareArrays(leftArrayValue, rightArrayValue); - } - function compareMaps(left, right) { - if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { - return 0; - } - else if (left === MAX_VALUE.mapValue) { - return 1; - } - else if (right === MAX_VALUE.mapValue) { - return -1; - } - const leftMap = left.fields || {}; - const leftKeys = Object.keys(leftMap); - const rightMap = right.fields || {}; - const rightKeys = Object.keys(rightMap); - // Even though MapValues are likely sorted correctly based on their insertion - // order (e.g. when received from the backend), local modifications can bring - // elements out of order. We need to re-sort the elements to ensure that - // canonical IDs are independent of insertion order. - leftKeys.sort(); - rightKeys.sort(); - for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { - const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]); - if (keyCompare !== 0) { - return keyCompare; - } - const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); - if (compare !== 0) { - return compare; - } - } - return primitiveComparator(leftKeys.length, rightKeys.length); - } - /** Returns a reference value for the provided database and key. */ - function refValue(databaseId, key) { - return { - referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` - }; - } - /** Returns true if `value` is an ArrayValue. */ - function isArray(value) { - return !!value && 'arrayValue' in value; - } - /** Returns true if `value` is a NullValue. */ - function isNullValue(value) { - return !!value && 'nullValue' in value; - } - /** Returns true if `value` is NaN. */ - function isNanValue(value) { - return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); - } - /** Returns true if `value` is a MapValue. */ - function isMapValue(value) { - return !!value && 'mapValue' in value; - } - /** Returns true if `value` is a VetorValue. */ - function isVectorValue(value) { - var _a, _b; - const type = (_b = (((_a = value === null || value === void 0 ? void 0 : value.mapValue) === null || _a === void 0 ? void 0 : _a.fields) || {})[TYPE_KEY]) === null || _b === void 0 ? void 0 : _b.stringValue; - return type === VECTOR_VALUE_SENTINEL; - } - /** Creates a deep copy of `source`. */ - function deepClone(source) { - if (source.geoPointValue) { - return { geoPointValue: Object.assign({}, source.geoPointValue) }; - } - else if (source.timestampValue && - typeof source.timestampValue === 'object') { - return { timestampValue: Object.assign({}, source.timestampValue) }; - } - else if (source.mapValue) { - const target = { mapValue: { fields: {} } }; - forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); - return target; - } - else if (source.arrayValue) { - const target = { arrayValue: { values: [] } }; - for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { - target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); - } - return target; - } - else { - return Object.assign({}, source); - } - } - /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ - function isMaxValue(value) { - return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === - MAX_VALUE_TYPE); - } - - /** - * @license - * Copyright 2022 Google LLC - * - * 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. - */ - /** - * Represents a bound of a query. - * - * The bound is specified with the given components representing a position and - * whether it's just before or just after the position (relative to whatever the - * query order is). - * - * The position represents a logical index position for a query. It's a prefix - * of values for the (potentially implicit) order by clauses of a query. - * - * Bound provides a function to determine whether a document comes before or - * after a bound. This is influenced by whether the position is just before or - * just after the provided values. - */ - class Bound { - constructor(position, inclusive) { - this.position = position; - this.inclusive = inclusive; - } - } - function boundEquals(left, right) { - if (left === null) { - return right === null; - } - else if (right === null) { - return false; - } - if (left.inclusive !== right.inclusive || - left.position.length !== right.position.length) { - return false; - } - for (let i = 0; i < left.position.length; i++) { - const leftPosition = left.position[i]; - const rightPosition = right.position[i]; - if (!valueEquals(leftPosition, rightPosition)) { - return false; - } - } - return true; - } - - /** - * @license - * Copyright 2022 Google LLC - * - * 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. - */ - class Filter { - } - class FieldFilter extends Filter { - constructor(field, op, value) { - super(); - this.field = field; - this.op = op; - this.value = value; - } - /** - * Creates a filter based on the provided arguments. - */ - static create(field, op, value) { - if (field.isKeyField()) { - if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { - return this.createKeyFieldInFilter(field, op, value); - } - else { - return new KeyFieldFilter(field, op, value); - } - } - else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { - return new ArrayContainsFilter(field, value); - } - else if (op === "in" /* Operator.IN */) { - return new InFilter(field, value); - } - else if (op === "not-in" /* Operator.NOT_IN */) { - return new NotInFilter(field, value); - } - else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { - return new ArrayContainsAnyFilter(field, value); - } - else { - return new FieldFilter(field, op, value); - } - } - static createKeyFieldInFilter(field, op, value) { - return op === "in" /* Operator.IN */ - ? new KeyFieldInFilter(field, value) - : new KeyFieldNotInFilter(field, value); - } - matches(doc) { - const other = doc.data.field(this.field); - // Types do not have to match in NOT_EQUAL filters. - if (this.op === "!=" /* Operator.NOT_EQUAL */) { - return (other !== null && - this.matchesComparison(valueCompare(other, this.value))); - } - // Only compare types with matching backend order (such as double and int). - return (other !== null && - typeOrder(this.value) === typeOrder(other) && - this.matchesComparison(valueCompare(other, this.value))); - } - matchesComparison(comparison) { - switch (this.op) { - case "<" /* Operator.LESS_THAN */: - return comparison < 0; - case "<=" /* Operator.LESS_THAN_OR_EQUAL */: - return comparison <= 0; - case "==" /* Operator.EQUAL */: - return comparison === 0; - case "!=" /* Operator.NOT_EQUAL */: - return comparison !== 0; - case ">" /* Operator.GREATER_THAN */: - return comparison > 0; - case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: - return comparison >= 0; - default: - return fail(); - } - } - isInequality() { - return ([ - "<" /* Operator.LESS_THAN */, - "<=" /* Operator.LESS_THAN_OR_EQUAL */, - ">" /* Operator.GREATER_THAN */, - ">=" /* Operator.GREATER_THAN_OR_EQUAL */, - "!=" /* Operator.NOT_EQUAL */, - "not-in" /* Operator.NOT_IN */ - ].indexOf(this.op) >= 0); - } - getFlattenedFilters() { - return [this]; - } - getFilters() { - return [this]; - } - } - class CompositeFilter extends Filter { - constructor(filters, op) { - super(); - this.filters = filters; - this.op = op; - this.memoizedFlattenedFilters = null; - } - /** - * Creates a filter based on the provided arguments. - */ - static create(filters, op) { - return new CompositeFilter(filters, op); - } - matches(doc) { - if (compositeFilterIsConjunction(this)) { - // For conjunctions, all filters must match, so return false if any filter doesn't match. - return this.filters.find(filter => !filter.matches(doc)) === undefined; - } - else { - // For disjunctions, at least one filter should match. - return this.filters.find(filter => filter.matches(doc)) !== undefined; - } - } - getFlattenedFilters() { - if (this.memoizedFlattenedFilters !== null) { - return this.memoizedFlattenedFilters; - } - this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { - return result.concat(subfilter.getFlattenedFilters()); - }, []); - return this.memoizedFlattenedFilters; - } - // Returns a mutable copy of `this.filters` - getFilters() { - return Object.assign([], this.filters); - } - } - function compositeFilterIsConjunction(compositeFilter) { - return compositeFilter.op === "and" /* CompositeOperator.AND */; - } - function filterEquals(f1, f2) { - if (f1 instanceof FieldFilter) { - return fieldFilterEquals(f1, f2); - } - else if (f1 instanceof CompositeFilter) { - return compositeFilterEquals(f1, f2); - } - else { - fail(); - } - } - function fieldFilterEquals(f1, f2) { - return (f2 instanceof FieldFilter && - f1.op === f2.op && - f1.field.isEqual(f2.field) && - valueEquals(f1.value, f2.value)); - } - function compositeFilterEquals(f1, f2) { - if (f2 instanceof CompositeFilter && - f1.op === f2.op && - f1.filters.length === f2.filters.length) { - const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); - return subFiltersMatch; - } - return false; - } - /** Filter that matches on key fields (i.e. '__name__'). */ - class KeyFieldFilter extends FieldFilter { - constructor(field, op, value) { - super(field, op, value); - this.key = DocumentKey.fromName(value.referenceValue); - } - matches(doc) { - const comparison = DocumentKey.comparator(doc.key, this.key); - return this.matchesComparison(comparison); - } - } - /** Filter that matches on key fields within an array. */ - class KeyFieldInFilter extends FieldFilter { - constructor(field, value) { - super(field, "in" /* Operator.IN */, value); - this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); - } - matches(doc) { - return this.keys.some(key => key.isEqual(doc.key)); - } - } - /** Filter that matches on key fields not present within an array. */ - class KeyFieldNotInFilter extends FieldFilter { - constructor(field, value) { - super(field, "not-in" /* Operator.NOT_IN */, value); - this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); - } - matches(doc) { - return !this.keys.some(key => key.isEqual(doc.key)); - } - } - function extractDocumentKeysFromArrayValue(op, value) { - var _a; - return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => { - return DocumentKey.fromName(v.referenceValue); - }); - } - /** A Filter that implements the array-contains operator. */ - class ArrayContainsFilter extends FieldFilter { - constructor(field, value) { - super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); - } - matches(doc) { - const other = doc.data.field(this.field); - return isArray(other) && arrayValueContains(other.arrayValue, this.value); - } - } - /** A Filter that implements the IN operator. */ - class InFilter extends FieldFilter { - constructor(field, value) { - super(field, "in" /* Operator.IN */, value); - } - matches(doc) { - const other = doc.data.field(this.field); - return other !== null && arrayValueContains(this.value.arrayValue, other); - } - } - /** A Filter that implements the not-in operator. */ - class NotInFilter extends FieldFilter { - constructor(field, value) { - super(field, "not-in" /* Operator.NOT_IN */, value); - } - matches(doc) { - if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { - return false; - } - const other = doc.data.field(this.field); - return other !== null && !arrayValueContains(this.value.arrayValue, other); - } - } - /** A Filter that implements the array-contains-any operator. */ - class ArrayContainsAnyFilter extends FieldFilter { - constructor(field, value) { - super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); - } - matches(doc) { - const other = doc.data.field(this.field); - if (!isArray(other) || !other.arrayValue.values) { - return false; - } - return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); - } - } - - /** - * @license - * Copyright 2022 Google LLC - * - * 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. - */ - /** - * An ordering on a field, in some Direction. Direction defaults to ASCENDING. - */ - class OrderBy { - constructor(field, dir = "asc" /* Direction.ASCENDING */) { - this.field = field; - this.dir = dir; - } - } - function orderByEquals(left, right) { - return left.dir === right.dir && left.field.isEqual(right.field); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * A version of a document in Firestore. This corresponds to the version - * timestamp, such as update_time or read_time. - */ - class SnapshotVersion { - constructor(timestamp) { - this.timestamp = timestamp; - } - static fromTimestamp(value) { - return new SnapshotVersion(value); - } - static min() { - return new SnapshotVersion(new Timestamp(0, 0)); - } - static max() { - return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); - } - compareTo(other) { - return this.timestamp._compareTo(other.timestamp); - } - isEqual(other) { - return this.timestamp.isEqual(other.timestamp); - } - /** Returns a number representation of the version for use in spec tests. */ - toMicroseconds() { - // Convert to microseconds. - return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; - } - toString() { - return 'SnapshotVersion(' + this.timestamp.toString() + ')'; - } - toTimestamp() { - return this.timestamp; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - // An immutable sorted map implementation, based on a Left-leaning Red-Black - // tree. - class SortedMap { - constructor(comparator, root) { - this.comparator = comparator; - this.root = root ? root : LLRBNode.EMPTY; - } - // Returns a copy of the map, with the specified key/value added or replaced. - insert(key, value) { - return new SortedMap(this.comparator, this.root - .insert(key, value, this.comparator) - .copy(null, null, LLRBNode.BLACK, null, null)); - } - // Returns a copy of the map, with the specified key removed. - remove(key) { - return new SortedMap(this.comparator, this.root - .remove(key, this.comparator) - .copy(null, null, LLRBNode.BLACK, null, null)); - } - // Returns the value of the node with the given key, or null. - get(key) { - let node = this.root; - while (!node.isEmpty()) { - const cmp = this.comparator(key, node.key); - if (cmp === 0) { - return node.value; - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - node = node.right; - } - } - return null; - } - // Returns the index of the element in this sorted map, or -1 if it doesn't - // exist. - indexOf(key) { - // Number of nodes that were pruned when descending right - let prunedNodes = 0; - let node = this.root; - while (!node.isEmpty()) { - const cmp = this.comparator(key, node.key); - if (cmp === 0) { - return prunedNodes + node.left.size; - } - else if (cmp < 0) { - node = node.left; - } - else { - // Count all nodes left of the node plus the node itself - prunedNodes += node.left.size + 1; - node = node.right; - } - } - // Node not found - return -1; - } - isEmpty() { - return this.root.isEmpty(); - } - // Returns the total number of nodes in the map. - get size() { - return this.root.size; - } - // Returns the minimum key in the map. - minKey() { - return this.root.minKey(); - } - // Returns the maximum key in the map. - maxKey() { - return this.root.maxKey(); - } - // Traverses the map in key order and calls the specified action function - // for each key/value pair. If action returns true, traversal is aborted. - // Returns the first truthy value returned by action, or the last falsey - // value returned by action. - inorderTraversal(action) { - return this.root.inorderTraversal(action); - } - forEach(fn) { - this.inorderTraversal((k, v) => { - fn(k, v); - return false; - }); - } - toString() { - const descriptions = []; - this.inorderTraversal((k, v) => { - descriptions.push(`${k}:${v}`); - return false; - }); - return `{${descriptions.join(', ')}}`; - } - // Traverses the map in reverse key order and calls the specified action - // function for each key/value pair. If action returns true, traversal is - // aborted. - // Returns the first truthy value returned by action, or the last falsey - // value returned by action. - reverseTraversal(action) { - return this.root.reverseTraversal(action); - } - // Returns an iterator over the SortedMap. - getIterator() { - return new SortedMapIterator(this.root, null, this.comparator, false); - } - getIteratorFrom(key) { - return new SortedMapIterator(this.root, key, this.comparator, false); - } - getReverseIterator() { - return new SortedMapIterator(this.root, null, this.comparator, true); - } - getReverseIteratorFrom(key) { - return new SortedMapIterator(this.root, key, this.comparator, true); - } - } // end SortedMap - // An iterator over an LLRBNode. - class SortedMapIterator { - constructor(node, startKey, comparator, isReverse) { - this.isReverse = isReverse; - this.nodeStack = []; - let cmp = 1; - while (!node.isEmpty()) { - cmp = startKey ? comparator(node.key, startKey) : 1; - // flip the comparison if we're going in reverse - if (startKey && isReverse) { - cmp *= -1; - } - if (cmp < 0) { - // This node is less than our start key. ignore it - if (this.isReverse) { - node = node.left; - } - else { - node = node.right; - } - } - else if (cmp === 0) { - // This node is exactly equal to our start key. Push it on the stack, - // but stop iterating; - this.nodeStack.push(node); - break; - } - else { - // This node is greater than our start key, add it to the stack and move - // to the next one - this.nodeStack.push(node); - if (this.isReverse) { - node = node.right; - } - else { - node = node.left; - } - } - } - } - getNext() { - let node = this.nodeStack.pop(); - const result = { key: node.key, value: node.value }; - if (this.isReverse) { - node = node.left; - while (!node.isEmpty()) { - this.nodeStack.push(node); - node = node.right; - } - } - else { - node = node.right; - while (!node.isEmpty()) { - this.nodeStack.push(node); - node = node.left; - } - } - return result; - } - hasNext() { - return this.nodeStack.length > 0; - } - peek() { - if (this.nodeStack.length === 0) { - return null; - } - const node = this.nodeStack[this.nodeStack.length - 1]; - return { key: node.key, value: node.value }; - } - } // end SortedMapIterator - // Represents a node in a Left-leaning Red-Black tree. - class LLRBNode { - constructor(key, value, color, left, right) { - this.key = key; - this.value = value; - this.color = color != null ? color : LLRBNode.RED; - this.left = left != null ? left : LLRBNode.EMPTY; - this.right = right != null ? right : LLRBNode.EMPTY; - this.size = this.left.size + 1 + this.right.size; - } - // Returns a copy of the current node, optionally replacing pieces of it. - copy(key, value, color, left, right) { - return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); - } - isEmpty() { - return false; - } - // Traverses the tree in key order and calls the specified action function - // for each node. If action returns true, traversal is aborted. - // Returns the first truthy value returned by action, or the last falsey - // value returned by action. - inorderTraversal(action) { - return (this.left.inorderTraversal(action) || - action(this.key, this.value) || - this.right.inorderTraversal(action)); - } - // Traverses the tree in reverse key order and calls the specified action - // function for each node. If action returns true, traversal is aborted. - // Returns the first truthy value returned by action, or the last falsey - // value returned by action. - reverseTraversal(action) { - return (this.right.reverseTraversal(action) || - action(this.key, this.value) || - this.left.reverseTraversal(action)); - } - // Returns the minimum node in the tree. - min() { - if (this.left.isEmpty()) { - return this; - } - else { - return this.left.min(); - } - } - // Returns the maximum key in the tree. - minKey() { - return this.min().key; - } - // Returns the maximum key in the tree. - maxKey() { - if (this.right.isEmpty()) { - return this.key; - } - else { - return this.right.maxKey(); - } - } - // Returns new tree, with the key/value added. - insert(key, value, comparator) { - let n = this; - const cmp = comparator(key, n.key); - if (cmp < 0) { - n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); - } - else if (cmp === 0) { - n = n.copy(null, value, null, null, null); - } - else { - n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); - } - return n.fixUp(); - } - removeMin() { - if (this.left.isEmpty()) { - return LLRBNode.EMPTY; - } - let n = this; - if (!n.left.isRed() && !n.left.left.isRed()) { - n = n.moveRedLeft(); - } - n = n.copy(null, null, null, n.left.removeMin(), null); - return n.fixUp(); - } - // Returns new tree, with the specified item removed. - remove(key, comparator) { - let smallest; - let n = this; - if (comparator(key, n.key) < 0) { - if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { - n = n.moveRedLeft(); - } - n = n.copy(null, null, null, n.left.remove(key, comparator), null); - } - else { - if (n.left.isRed()) { - n = n.rotateRight(); - } - if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { - n = n.moveRedRight(); - } - if (comparator(key, n.key) === 0) { - if (n.right.isEmpty()) { - return LLRBNode.EMPTY; - } - else { - smallest = n.right.min(); - n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); - } - } - n = n.copy(null, null, null, null, n.right.remove(key, comparator)); - } - return n.fixUp(); - } - isRed() { - return this.color; - } - // Returns new tree after performing any needed rotations. - fixUp() { - let n = this; - if (n.right.isRed() && !n.left.isRed()) { - n = n.rotateLeft(); - } - if (n.left.isRed() && n.left.left.isRed()) { - n = n.rotateRight(); - } - if (n.left.isRed() && n.right.isRed()) { - n = n.colorFlip(); - } - return n; - } - moveRedLeft() { - let n = this.colorFlip(); - if (n.right.left.isRed()) { - n = n.copy(null, null, null, null, n.right.rotateRight()); - n = n.rotateLeft(); - n = n.colorFlip(); - } - return n; - } - moveRedRight() { - let n = this.colorFlip(); - if (n.left.left.isRed()) { - n = n.rotateRight(); - n = n.colorFlip(); - } - return n; - } - rotateLeft() { - const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); - return this.right.copy(null, null, this.color, nl, null); - } - rotateRight() { - const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); - return this.left.copy(null, null, this.color, null, nr); - } - colorFlip() { - const left = this.left.copy(null, null, !this.left.color, null, null); - const right = this.right.copy(null, null, !this.right.color, null, null); - return this.copy(null, null, !this.color, left, right); - } - // For testing. - checkMaxDepth() { - const blackDepth = this.check(); - if (Math.pow(2.0, blackDepth) <= this.size + 1) { - return true; - } - else { - return false; - } - } - // In a balanced RB tree, the black-depth (number of black nodes) from root to - // leaves is equal on both sides. This function verifies that or asserts. - check() { - if (this.isRed() && this.left.isRed()) { - throw fail(); - } - if (this.right.isRed()) { - throw fail(); - } - const blackDepth = this.left.check(); - if (blackDepth !== this.right.check()) { - throw fail(); - } - else { - return blackDepth + (this.isRed() ? 0 : 1); - } - } - } // end LLRBNode - // Empty node is shared between all LLRB trees. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - LLRBNode.EMPTY = null; - LLRBNode.RED = true; - LLRBNode.BLACK = false; - // Represents an empty node (a leaf node in the Red-Black Tree). - class LLRBEmptyNode { - constructor() { - this.size = 0; - } - get key() { - throw fail(); - } - get value() { - throw fail(); - } - get color() { - throw fail(); - } - get left() { - throw fail(); - } - get right() { - throw fail(); - } - // Returns a copy of the current node. - copy(key, value, color, left, right) { - return this; - } - // Returns a copy of the tree, with the specified key/value added. - insert(key, value, comparator) { - return new LLRBNode(key, value); - } - // Returns a copy of the tree, with the specified key removed. - remove(key, comparator) { - return this; - } - isEmpty() { - return true; - } - inorderTraversal(action) { - return false; - } - reverseTraversal(action) { - return false; - } - minKey() { - return null; - } - maxKey() { - return null; - } - isRed() { - return false; - } - // For testing. - checkMaxDepth() { - return true; - } - check() { - return 0; - } - } // end LLRBEmptyNode - LLRBNode.EMPTY = new LLRBEmptyNode(); - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * SortedSet is an immutable (copy-on-write) collection that holds elements - * in order specified by the provided comparator. - * - * NOTE: if provided comparator returns 0 for two elements, we consider them to - * be equal! - */ - class SortedSet { - constructor(comparator) { - this.comparator = comparator; - this.data = new SortedMap(this.comparator); - } - has(elem) { - return this.data.get(elem) !== null; - } - first() { - return this.data.minKey(); - } - last() { - return this.data.maxKey(); - } - get size() { - return this.data.size; - } - indexOf(elem) { - return this.data.indexOf(elem); - } - /** Iterates elements in order defined by "comparator" */ - forEach(cb) { - this.data.inorderTraversal((k, v) => { - cb(k); - return false; - }); - } - /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ - forEachInRange(range, cb) { - const iter = this.data.getIteratorFrom(range[0]); - while (iter.hasNext()) { - const elem = iter.getNext(); - if (this.comparator(elem.key, range[1]) >= 0) { - return; - } - cb(elem.key); - } - } - /** - * Iterates over `elem`s such that: start <= elem until false is returned. - */ - forEachWhile(cb, start) { - let iter; - if (start !== undefined) { - iter = this.data.getIteratorFrom(start); - } - else { - iter = this.data.getIterator(); - } - while (iter.hasNext()) { - const elem = iter.getNext(); - const result = cb(elem.key); - if (!result) { - return; - } - } - } - /** Finds the least element greater than or equal to `elem`. */ - firstAfterOrEqual(elem) { - const iter = this.data.getIteratorFrom(elem); - return iter.hasNext() ? iter.getNext().key : null; - } - getIterator() { - return new SortedSetIterator(this.data.getIterator()); - } - getIteratorFrom(key) { - return new SortedSetIterator(this.data.getIteratorFrom(key)); - } - /** Inserts or updates an element */ - add(elem) { - return this.copy(this.data.remove(elem).insert(elem, true)); - } - /** Deletes an element */ - delete(elem) { - if (!this.has(elem)) { - return this; - } - return this.copy(this.data.remove(elem)); - } - isEmpty() { - return this.data.isEmpty(); - } - unionWith(other) { - let result = this; - // Make sure `result` always refers to the larger one of the two sets. - if (result.size < other.size) { - result = other; - other = this; - } - other.forEach(elem => { - result = result.add(elem); - }); - return result; - } - isEqual(other) { - if (!(other instanceof SortedSet)) { - return false; - } - if (this.size !== other.size) { - return false; - } - const thisIt = this.data.getIterator(); - const otherIt = other.data.getIterator(); - while (thisIt.hasNext()) { - const thisElem = thisIt.getNext().key; - const otherElem = otherIt.getNext().key; - if (this.comparator(thisElem, otherElem) !== 0) { - return false; - } - } - return true; - } - toArray() { - const res = []; - this.forEach(targetId => { - res.push(targetId); - }); - return res; - } - toString() { - const result = []; - this.forEach(elem => result.push(elem)); - return 'SortedSet(' + result.toString() + ')'; - } - copy(data) { - const result = new SortedSet(this.comparator); - result.data = data; - return result; - } - } - class SortedSetIterator { - constructor(iter) { - this.iter = iter; - } - getNext() { - return this.iter.getNext().key; - } - hasNext() { - return this.iter.hasNext(); - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Provides a set of fields that can be used to partially patch a document. - * FieldMask is used in conjunction with ObjectValue. - * Examples: - * foo - Overwrites foo entirely with the provided value. If foo is not - * present in the companion ObjectValue, the field is deleted. - * foo.bar - Overwrites only the field bar of the object foo. - * If foo is not an object, foo is replaced with an object - * containing foo - */ - class FieldMask { - constructor(fields) { - this.fields = fields; - // TODO(dimond): validation of FieldMask - // Sort the field mask to support `FieldMask.isEqual()` and assert below. - fields.sort(FieldPath$1.comparator); - } - static empty() { - return new FieldMask([]); - } - /** - * Returns a new FieldMask object that is the result of adding all the given - * fields paths to this field mask. - */ - unionWith(extraFields) { - let mergedMaskSet = new SortedSet(FieldPath$1.comparator); - for (const fieldPath of this.fields) { - mergedMaskSet = mergedMaskSet.add(fieldPath); - } - for (const fieldPath of extraFields) { - mergedMaskSet = mergedMaskSet.add(fieldPath); - } - return new FieldMask(mergedMaskSet.toArray()); - } - /** - * Verifies that `fieldPath` is included by at least one field in this field - * mask. - * - * This is an O(n) operation, where `n` is the size of the field mask. - */ - covers(fieldPath) { - for (const fieldMaskPath of this.fields) { - if (fieldMaskPath.isPrefixOf(fieldPath)) { - return true; - } - } - return false; - } - isEqual(other) { - return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * An ObjectValue represents a MapValue in the Firestore Proto and offers the - * ability to add and remove fields (via the ObjectValueBuilder). - */ - class ObjectValue { - constructor(value) { - this.value = value; - } - static empty() { - return new ObjectValue({ mapValue: {} }); - } - /** - * Returns the value at the given path or null. - * - * @param path - the path to search - * @returns The value at the path or null if the path is not set. - */ - field(path) { - if (path.isEmpty()) { - return this.value; - } - else { - let currentLevel = this.value; - for (let i = 0; i < path.length - 1; ++i) { - currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; - if (!isMapValue(currentLevel)) { - return null; - } - } - currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; - return currentLevel || null; - } - } - /** - * Sets the field to the provided value. - * - * @param path - The field path to set. - * @param value - The value to set. - */ - set(path, value) { - const fieldsMap = this.getFieldsMap(path.popLast()); - fieldsMap[path.lastSegment()] = deepClone(value); - } - /** - * Sets the provided fields to the provided values. - * - * @param data - A map of fields to values (or null for deletes). - */ - setAll(data) { - let parent = FieldPath$1.emptyPath(); - let upserts = {}; - let deletes = []; - data.forEach((value, path) => { - if (!parent.isImmediateParentOf(path)) { - // Insert the accumulated changes at this parent location - const fieldsMap = this.getFieldsMap(parent); - this.applyChanges(fieldsMap, upserts, deletes); - upserts = {}; - deletes = []; - parent = path.popLast(); - } - if (value) { - upserts[path.lastSegment()] = deepClone(value); - } - else { - deletes.push(path.lastSegment()); - } - }); - const fieldsMap = this.getFieldsMap(parent); - this.applyChanges(fieldsMap, upserts, deletes); - } - /** - * Removes the field at the specified path. If there is no field at the - * specified path, nothing is changed. - * - * @param path - The field path to remove. - */ - delete(path) { - const nestedValue = this.field(path.popLast()); - if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { - delete nestedValue.mapValue.fields[path.lastSegment()]; - } - } - isEqual(other) { - return valueEquals(this.value, other.value); - } - /** - * Returns the map that contains the leaf element of `path`. If the parent - * entry does not yet exist, or if it is not a map, a new map will be created. - */ - getFieldsMap(path) { - let current = this.value; - if (!current.mapValue.fields) { - current.mapValue = { fields: {} }; - } - for (let i = 0; i < path.length; ++i) { - let next = current.mapValue.fields[path.get(i)]; - if (!isMapValue(next) || !next.mapValue.fields) { - next = { mapValue: { fields: {} } }; - current.mapValue.fields[path.get(i)] = next; - } - current = next; - } - return current.mapValue.fields; - } - /** - * Modifies `fieldsMap` by adding, replacing or deleting the specified - * entries. - */ - applyChanges(fieldsMap, inserts, deletes) { - forEach(inserts, (key, val) => (fieldsMap[key] = val)); - for (const field of deletes) { - delete fieldsMap[field]; - } - } - clone() { - return new ObjectValue(deepClone(this.value)); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Represents a document in Firestore with a key, version, data and whether it - * has local mutations applied to it. - * - * Documents can transition between states via `convertToFoundDocument()`, - * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does - * not transition to one of these states even after all mutations have been - * applied, `isValidDocument()` returns false and the document should be removed - * from all views. - */ - class MutableDocument { - constructor(key, documentType, version, readTime, createTime, data, documentState) { - this.key = key; - this.documentType = documentType; - this.version = version; - this.readTime = readTime; - this.createTime = createTime; - this.data = data; - this.documentState = documentState; - } - /** - * Creates a document with no known version or data, but which can serve as - * base document for mutations. - */ - static newInvalidDocument(documentKey) { - return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, - /* version */ SnapshotVersion.min(), - /* readTime */ SnapshotVersion.min(), - /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); - } - /** - * Creates a new document that is known to exist with the given data at the - * given version. - */ - static newFoundDocument(documentKey, version, createTime, value) { - return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, - /* version */ version, - /* readTime */ SnapshotVersion.min(), - /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); - } - /** Creates a new document that is known to not exist at the given version. */ - static newNoDocument(documentKey, version) { - return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, - /* version */ version, - /* readTime */ SnapshotVersion.min(), - /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); - } - /** - * Creates a new document that is known to exist at the given version but - * whose data is not known (e.g. a document that was updated without a known - * base document). - */ - static newUnknownDocument(documentKey, version) { - return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, - /* version */ version, - /* readTime */ SnapshotVersion.min(), - /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); - } - /** - * Changes the document type to indicate that it exists and that its version - * and data are known. - */ - convertToFoundDocument(version, value) { - // If a document is switching state from being an invalid or deleted - // document to a valid (FOUND_DOCUMENT) document, either due to receiving an - // update from Watch or due to applying a local set mutation on top - // of a deleted document, our best guess about its createTime would be the - // version at which the document transitioned to a FOUND_DOCUMENT. - if (this.createTime.isEqual(SnapshotVersion.min()) && - (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || - this.documentType === 0 /* DocumentType.INVALID */)) { - this.createTime = version; - } - this.version = version; - this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; - this.data = value; - this.documentState = 0 /* DocumentState.SYNCED */; - return this; - } - /** - * Changes the document type to indicate that it doesn't exist at the given - * version. - */ - convertToNoDocument(version) { - this.version = version; - this.documentType = 2 /* DocumentType.NO_DOCUMENT */; - this.data = ObjectValue.empty(); - this.documentState = 0 /* DocumentState.SYNCED */; - return this; - } - /** - * Changes the document type to indicate that it exists at a given version but - * that its data is not known (e.g. a document that was updated without a known - * base document). - */ - convertToUnknownDocument(version) { - this.version = version; - this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; - this.data = ObjectValue.empty(); - this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; - return this; - } - setHasCommittedMutations() { - this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; - return this; - } - setHasLocalMutations() { - this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; - this.version = SnapshotVersion.min(); - return this; - } - setReadTime(readTime) { - this.readTime = readTime; - return this; - } - get hasLocalMutations() { - return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; - } - get hasCommittedMutations() { - return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; - } - get hasPendingWrites() { - return this.hasLocalMutations || this.hasCommittedMutations; - } - isValidDocument() { - return this.documentType !== 0 /* DocumentType.INVALID */; - } - isFoundDocument() { - return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; - } - isNoDocument() { - return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; - } - isUnknownDocument() { - return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; - } - isEqual(other) { - return (other instanceof MutableDocument && - this.key.isEqual(other.key) && - this.version.isEqual(other.version) && - this.documentType === other.documentType && - this.documentState === other.documentState && - this.data.isEqual(other.data)); - } - mutableCopy() { - return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); - } - toString() { - return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + - `{createTime: ${this.createTime}}), ` + - `{documentType: ${this.documentType}}), ` + - `{documentState: ${this.documentState}})`); - } - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - // Visible for testing - class TargetImpl { - constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { - this.path = path; - this.collectionGroup = collectionGroup; - this.orderBy = orderBy; - this.filters = filters; - this.limit = limit; - this.startAt = startAt; - this.endAt = endAt; - this.memoizedCanonicalId = null; - } - } - /** - * Initializes a Target with a path and optional additional query constraints. - * Path must currently be empty if this is a collection group query. - * - * NOTE: you should always construct `Target` from `Query.toTarget` instead of - * using this factory method, because `Query` provides an implicit `orderBy` - * property. - */ - function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { - return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); - } - function targetEquals(left, right) { - if (left.limit !== right.limit) { - return false; - } - if (left.orderBy.length !== right.orderBy.length) { - return false; - } - for (let i = 0; i < left.orderBy.length; i++) { - if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { - return false; - } - } - if (left.filters.length !== right.filters.length) { - return false; - } - for (let i = 0; i < left.filters.length; i++) { - if (!filterEquals(left.filters[i], right.filters[i])) { - return false; - } - } - if (left.collectionGroup !== right.collectionGroup) { - return false; - } - if (!left.path.isEqual(right.path)) { - return false; - } - if (!boundEquals(left.startAt, right.startAt)) { - return false; - } - return boundEquals(left.endAt, right.endAt); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Query encapsulates all the query attributes we support in the SDK. It can - * be run against the LocalStore, as well as be converted to a `Target` to - * query the RemoteStore results. - * - * Visible for testing. - */ - class QueryImpl { - /** - * Initializes a Query with a path and optional additional query constraints. - * Path must currently be empty if this is a collection group query. - */ - constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { - this.path = path; - this.collectionGroup = collectionGroup; - this.explicitOrderBy = explicitOrderBy; - this.filters = filters; - this.limit = limit; - this.limitType = limitType; - this.startAt = startAt; - this.endAt = endAt; - this.memoizedNormalizedOrderBy = null; - // The corresponding `Target` of this `Query` instance, for use with - // non-aggregate queries. - this.memoizedTarget = null; - // The corresponding `Target` of this `Query` instance, for use with - // aggregate queries. Unlike targets for non-aggregate queries, - // aggregate query targets do not contain normalized order-bys, they only - // contain explicit order-bys. - this.memoizedAggregateTarget = null; - if (this.startAt) ; - if (this.endAt) ; - } - } - /** Creates a new Query for a query that matches all documents at `path` */ - function newQueryForPath(path) { - return new QueryImpl(path); - } - // Returns the sorted set of inequality filter fields used in this query. - function getInequalityFilterFields(query) { - let result = new SortedSet(FieldPath$1.comparator); - query.filters.forEach((filter) => { - const subFilters = filter.getFlattenedFilters(); - subFilters.forEach((filter) => { - if (filter.isInequality()) { - result = result.add(filter.field); - } - }); - }); - return result; - } - /** - * Creates a new Query for a collection group query that matches all documents - * within the provided collection group. - */ - function newQueryForCollectionGroup(collectionId) { - return new QueryImpl(ResourcePath.emptyPath(), collectionId); - } - /** - * Returns whether the query matches a collection group rather than a specific - * collection. - */ - function isCollectionGroupQuery(query) { - return query.collectionGroup !== null; - } - /** - * Returns the normalized order-by constraint that is used to execute the Query, - * which can be different from the order-by constraints the user provided (e.g. - * the SDK and backend always orders by `__name__`). The normalized order-by - * includes implicit order-bys in addition to the explicit user provided - * order-bys. - */ - function queryNormalizedOrderBy(query) { - const queryImpl = debugCast(query); - if (queryImpl.memoizedNormalizedOrderBy === null) { - queryImpl.memoizedNormalizedOrderBy = []; - const fieldsNormalized = new Set(); - // Any explicit order by fields should be added as is. - for (const orderBy of queryImpl.explicitOrderBy) { - queryImpl.memoizedNormalizedOrderBy.push(orderBy); - fieldsNormalized.add(orderBy.field.canonicalString()); - } - // The order of the implicit ordering always matches the last explicit order by. - const lastDirection = queryImpl.explicitOrderBy.length > 0 - ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir - : "asc" /* Direction.ASCENDING */; - // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical - // order. When there are multiple inequality filters on the same field, the field should be added - // only once. - // Note: `SortedSet` sorts the key field before other fields. However, we want the key - // field to be sorted last. - const inequalityFields = getInequalityFilterFields(queryImpl); - inequalityFields.forEach(field => { - if (!fieldsNormalized.has(field.canonicalString()) && - !field.isKeyField()) { - queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); - } - }); - // Add the document key field to the last if it is not explicitly ordered. - if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { - queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); - } - } - return queryImpl.memoizedNormalizedOrderBy; - } - /** - * Converts this `Query` instance to its corresponding `Target` representation. - */ - function queryToTarget(query) { - const queryImpl = debugCast(query); - if (!queryImpl.memoizedTarget) { - queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); - } - return queryImpl.memoizedTarget; - } - /** - * Converts this `Query` instance to its corresponding `Target` representation, - * for use within an aggregate query. Unlike targets for non-aggregate queries, - * aggregate query targets do not contain normalized order-bys, they only - * contain explicit order-bys. - */ - function queryToAggregateTarget(query) { - const queryImpl = debugCast(query); - if (!queryImpl.memoizedAggregateTarget) { - // Do not include implicit order-bys for aggregate queries. - queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); - } - return queryImpl.memoizedAggregateTarget; - } - function _queryToTarget(queryImpl, orderBys) { - if (queryImpl.limitType === "F" /* LimitType.First */) { - return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); - } - else { - // Flip the orderBy directions since we want the last results - orderBys = orderBys.map(orderBy => { - const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ - ? "asc" /* Direction.ASCENDING */ - : "desc" /* Direction.DESCENDING */; - return new OrderBy(orderBy.field, dir); - }); - // We need to swap the cursors to match the now-flipped query ordering. - const startAt = queryImpl.endAt - ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) - : null; - const endAt = queryImpl.startAt - ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) - : null; - // Now return as a LimitType.First query. - return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); - } - } - function queryWithAddedFilter(query, filter) { - const newFilters = query.filters.concat([filter]); - return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); - } - function queryWithAddedOrderBy(query, orderBy) { - // TODO(dimond): validate that orderBy does not list the same key twice. - const newOrderBy = query.explicitOrderBy.concat([orderBy]); - return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); - } - function queryWithLimit(query, limit, limitType) { - return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); - } - function queryWithStartAt(query, bound) { - return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); - } - function queryWithEndAt(query, bound) { - return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); - } - function queryEquals(left, right) { - return (targetEquals(queryToTarget(left), queryToTarget(right)) && - left.limitType === right.limitType); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Returns an DoubleValue for `value` that is encoded based the serializer's - * `useProto3Json` setting. - */ - function toDouble(serializer, value) { - if (serializer.useProto3Json) { - if (isNaN(value)) { - return { doubleValue: 'NaN' }; - } - else if (value === Infinity) { - return { doubleValue: 'Infinity' }; - } - else if (value === -Infinity) { - return { doubleValue: '-Infinity' }; - } - } - return { doubleValue: isNegativeZero(value) ? '-0' : value }; - } - /** - * Returns an IntegerValue for `value`. - */ - function toInteger(value) { - return { integerValue: '' + value }; - } - /** - * Returns a value for a number that's appropriate to put into a proto. - * The return value is an IntegerValue if it can safely represent the value, - * otherwise a DoubleValue is returned. - */ - function toNumber(serializer, value) { - return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); - } - - /** - * @license - * Copyright 2018 Google LLC - * - * 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. - */ - /** Used to represent a field transform on a mutation. */ - class TransformOperation { - constructor() { - // Make sure that the structural type of `TransformOperation` is unique. - // See https://github.com/microsoft/TypeScript/issues/5451 - this._ = undefined; - } - } - /** Transforms a value into a server-generated timestamp. */ - class ServerTimestampTransform extends TransformOperation { - } - /** Transforms an array value via a union operation. */ - class ArrayUnionTransformOperation extends TransformOperation { - constructor(elements) { - super(); - this.elements = elements; - } - } - /** Transforms an array value via a remove operation. */ - class ArrayRemoveTransformOperation extends TransformOperation { - constructor(elements) { - super(); - this.elements = elements; - } - } - /** - * Implements the backend semantics for locally computed NUMERIC_ADD (increment) - * transforms. Converts all field values to integers or doubles, but unlike the - * backend does not cap integer values at 2^63. Instead, JavaScript number - * arithmetic is used and precision loss can occur for values greater than 2^53. - */ - class NumericIncrementTransformOperation extends TransformOperation { - constructor(serializer, operand) { - super(); - this.serializer = serializer; - this.operand = operand; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** A field path and the TransformOperation to perform upon it. */ - class FieldTransform { - constructor(field, transform) { - this.field = field; - this.transform = transform; - } - } - /** - * Encodes a precondition for a mutation. This follows the model that the - * backend accepts with the special case of an explicit "empty" precondition - * (meaning no precondition). - */ - class Precondition { - constructor(updateTime, exists) { - this.updateTime = updateTime; - this.exists = exists; - } - /** Creates a new empty Precondition. */ - static none() { - return new Precondition(); - } - /** Creates a new Precondition with an exists flag. */ - static exists(exists) { - return new Precondition(undefined, exists); - } - /** Creates a new Precondition based on a version a document exists at. */ - static updateTime(version) { - return new Precondition(version); - } - /** Returns whether this Precondition is empty. */ - get isNone() { - return this.updateTime === undefined && this.exists === undefined; - } - isEqual(other) { - return (this.exists === other.exists && - (this.updateTime - ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) - : !other.updateTime)); - } - } - /** - * A mutation describes a self-contained change to a document. Mutations can - * create, replace, delete, and update subsets of documents. - * - * Mutations not only act on the value of the document but also its version. - * - * For local mutations (mutations that haven't been committed yet), we preserve - * the existing version for Set and Patch mutations. For Delete mutations, we - * reset the version to 0. - * - * Here's the expected transition table. - * - * MUTATION APPLIED TO RESULTS IN - * - * SetMutation Document(v3) Document(v3) - * SetMutation NoDocument(v3) Document(v0) - * SetMutation InvalidDocument(v0) Document(v0) - * PatchMutation Document(v3) Document(v3) - * PatchMutation NoDocument(v3) NoDocument(v3) - * PatchMutation InvalidDocument(v0) UnknownDocument(v3) - * DeleteMutation Document(v3) NoDocument(v0) - * DeleteMutation NoDocument(v3) NoDocument(v0) - * DeleteMutation InvalidDocument(v0) NoDocument(v0) - * - * For acknowledged mutations, we use the updateTime of the WriteResponse as - * the resulting version for Set and Patch mutations. As deletes have no - * explicit update time, we use the commitTime of the WriteResponse for - * Delete mutations. - * - * If a mutation is acknowledged by the backend but fails the precondition check - * locally, we transition to an `UnknownDocument` and rely on Watch to send us - * the updated version. - * - * Field transforms are used only with Patch and Set Mutations. We use the - * `updateTransforms` message to store transforms, rather than the `transforms`s - * messages. - * - * ## Subclassing Notes - * - * Every type of mutation needs to implement its own applyToRemoteDocument() and - * applyToLocalView() to implement the actual behavior of applying the mutation - * to some source document (see `setMutationApplyToRemoteDocument()` for an - * example). - */ - class Mutation { - } - /** - * A mutation that creates or replaces the document at the given key with the - * object value contents. - */ - class SetMutation extends Mutation { - constructor(key, value, precondition, fieldTransforms = []) { - super(); - this.key = key; - this.value = value; - this.precondition = precondition; - this.fieldTransforms = fieldTransforms; - this.type = 0 /* MutationType.Set */; - } - getFieldMask() { - return null; - } - } - /** - * A mutation that modifies fields of the document at the given key with the - * given values. The values are applied through a field mask: - * - * * When a field is in both the mask and the values, the corresponding field - * is updated. - * * When a field is in neither the mask nor the values, the corresponding - * field is unmodified. - * * When a field is in the mask but not in the values, the corresponding field - * is deleted. - * * When a field is not in the mask but is in the values, the values map is - * ignored. - */ - class PatchMutation extends Mutation { - constructor(key, data, fieldMask, precondition, fieldTransforms = []) { - super(); - this.key = key; - this.data = data; - this.fieldMask = fieldMask; - this.precondition = precondition; - this.fieldTransforms = fieldTransforms; - this.type = 1 /* MutationType.Patch */; - } - getFieldMask() { - return this.fieldMask; - } - } - /** A mutation that deletes the document at the given key. */ - class DeleteMutation extends Mutation { - constructor(key, precondition) { - super(); - this.key = key; - this.precondition = precondition; - this.type = 2 /* MutationType.Delete */; - this.fieldTransforms = []; - } - getFieldMask() { - return null; - } - } - /** - * A mutation that verifies the existence of the document at the given key with - * the provided precondition. - * - * The `verify` operation is only used in Transactions, and this class serves - * primarily to facilitate serialization into protos. - */ - class VerifyMutation extends Mutation { - constructor(key, precondition) { - super(); - this.key = key; - this.precondition = precondition; - this.type = 3 /* MutationType.Verify */; - this.fieldTransforms = []; - } - getFieldMask() { - return null; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - const DIRECTIONS = (() => { - const dirs = {}; - dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; - dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; - return dirs; - })(); - const OPERATORS = (() => { - const ops = {}; - ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; - ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; - ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; - ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; - ops["==" /* Operator.EQUAL */] = 'EQUAL'; - ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; - ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; - ops["in" /* Operator.IN */] = 'IN'; - ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; - ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; - return ops; - })(); - const COMPOSITE_OPERATORS = (() => { - const ops = {}; - ops["and" /* CompositeOperator.AND */] = 'AND'; - ops["or" /* CompositeOperator.OR */] = 'OR'; - return ops; - })(); - function assertPresent(value, description) { - } - /** - * This class generates JsonObject values for the Datastore API suitable for - * sending to either GRPC stub methods or via the JSON/HTTP REST API. - * - * The serializer supports both Protobuf.js and Proto3 JSON formats. By - * setting `useProto3Json` to true, the serializer will use the Proto3 JSON - * format. - * - * For a description of the Proto3 JSON format check - * https://developers.google.com/protocol-buffers/docs/proto3#json - * - * TODO(klimt): We can remove the databaseId argument if we keep the full - * resource name in documents. - */ - class JsonProtoSerializer { - constructor(databaseId, useProto3Json) { - this.databaseId = databaseId; - this.useProto3Json = useProto3Json; - } - } - /** - * Returns a value for a number (or null) that's appropriate to put into - * a google.protobuf.Int32Value proto. - * DO NOT USE THIS FOR ANYTHING ELSE. - * This method cheats. It's typed as returning "number" because that's what - * our generated proto interfaces say Int32Value must be. But GRPC actually - * expects a { value: } struct. - */ - function toInt32Proto(serializer, val) { - if (serializer.useProto3Json || isNullOrUndefined(val)) { - return val; - } - else { - return { value: val }; - } - } - /** - * Returns a value for a Date that's appropriate to put into a proto. - */ - function toTimestamp(serializer, timestamp) { - if (serializer.useProto3Json) { - // Serialize to ISO-8601 date format, but with full nano resolution. - // Since JS Date has only millis, let's only use it for the seconds and - // then manually add the fractions to the end. - const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); - // Remove .xxx frac part and Z in the end. - const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); - // Pad the fraction out to 9 digits (nanos). - const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); - return `${strUntilSeconds}.${nanoStr}Z`; - } - else { - return { - seconds: '' + timestamp.seconds, - nanos: timestamp.nanoseconds - // eslint-disable-next-line @typescript-eslint/no-explicit-any - }; - } - } - function fromTimestamp(date) { - const timestamp = normalizeTimestamp(date); - return new Timestamp(timestamp.seconds, timestamp.nanos); - } - /** - * Returns a value for bytes that's appropriate to put in a proto. - * - * Visible for testing. - */ - function toBytes(serializer, bytes) { - if (serializer.useProto3Json) { - return bytes.toBase64(); - } - else { - return bytes.toUint8Array(); - } - } - function toVersion(serializer, version) { - return toTimestamp(serializer, version.toTimestamp()); - } - function fromVersion(version) { - hardAssert(!!version); - return SnapshotVersion.fromTimestamp(fromTimestamp(version)); - } - function toResourceName(databaseId, path) { - return toResourcePath(databaseId, path).canonicalString(); - } - function toResourcePath(databaseId, path) { - const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); - return path === undefined ? resourcePath : resourcePath.child(path); - } - function fromResourceName(name) { - const resource = ResourcePath.fromString(name); - hardAssert(isValidResourceName(resource)); - return resource; - } - function toName(serializer, key) { - return toResourceName(serializer.databaseId, key.path); - } - function fromName(serializer, name) { - const resource = fromResourceName(name); - if (resource.get(1) !== serializer.databaseId.projectId) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + - resource.get(1) + - ' vs ' + - serializer.databaseId.projectId); - } - if (resource.get(3) !== serializer.databaseId.database) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + - resource.get(3) + - ' vs ' + - serializer.databaseId.database); - } - return new DocumentKey(extractLocalPathFromResourceName(resource)); - } - function toQueryPath(serializer, path) { - return toResourceName(serializer.databaseId, path); - } - function fullyQualifiedPrefixPath(databaseId) { - return new ResourcePath([ - 'projects', - databaseId.projectId, - 'databases', - databaseId.database - ]); - } - function extractLocalPathFromResourceName(resourceName) { - hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents'); - return resourceName.popFirst(5); - } - /** Creates a Document proto from key and fields (but no create/update time) */ - function toMutationDocument(serializer, key, fields) { - return { - name: toName(serializer, key), - fields: fields.value.mapValue.fields - }; - } - function fromDocument(serializer, document, hasCommittedMutations) { - const key = fromName(serializer, document.name); - const version = fromVersion(document.updateTime); - // If we read a document from persistence that is missing createTime, it's due - // to older SDK versions not storing this information. In such cases, we'll - // set the createTime to zero. This can be removed in the long term. - const createTime = document.createTime - ? fromVersion(document.createTime) - : SnapshotVersion.min(); - const data = new ObjectValue({ mapValue: { fields: document.fields } }); - const result = MutableDocument.newFoundDocument(key, version, createTime, data); - if (hasCommittedMutations) { - result.setHasCommittedMutations(); - } - return hasCommittedMutations ? result.setHasCommittedMutations() : result; - } - function fromFound(serializer, doc) { - hardAssert(!!doc.found); - assertPresent(doc.found.name); - assertPresent(doc.found.updateTime); - const key = fromName(serializer, doc.found.name); - const version = fromVersion(doc.found.updateTime); - const createTime = doc.found.createTime - ? fromVersion(doc.found.createTime) - : SnapshotVersion.min(); - const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); - return MutableDocument.newFoundDocument(key, version, createTime, data); - } - function fromMissing(serializer, result) { - hardAssert(!!result.missing); - hardAssert(!!result.readTime); - const key = fromName(serializer, result.missing); - const version = fromVersion(result.readTime); - return MutableDocument.newNoDocument(key, version); - } - function fromBatchGetDocumentsResponse(serializer, result) { - if ('found' in result) { - return fromFound(serializer, result); - } - else if ('missing' in result) { - return fromMissing(serializer, result); - } - return fail(); - } - function toMutation(serializer, mutation) { - let result; - if (mutation instanceof SetMutation) { - result = { - update: toMutationDocument(serializer, mutation.key, mutation.value) - }; - } - else if (mutation instanceof DeleteMutation) { - result = { delete: toName(serializer, mutation.key) }; - } - else if (mutation instanceof PatchMutation) { - result = { - update: toMutationDocument(serializer, mutation.key, mutation.data), - updateMask: toDocumentMask(mutation.fieldMask) - }; - } - else if (mutation instanceof VerifyMutation) { - result = { - verify: toName(serializer, mutation.key) - }; - } - else { - return fail(); - } - if (mutation.fieldTransforms.length > 0) { - result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); - } - if (!mutation.precondition.isNone) { - result.currentDocument = toPrecondition(serializer, mutation.precondition); - } - return result; - } - function toPrecondition(serializer, precondition) { - if (precondition.updateTime !== undefined) { - return { - updateTime: toVersion(serializer, precondition.updateTime) - }; - } - else if (precondition.exists !== undefined) { - return { exists: precondition.exists }; - } - else { - return fail(); - } - } - function toFieldTransform(serializer, fieldTransform) { - const transform = fieldTransform.transform; - if (transform instanceof ServerTimestampTransform) { - return { - fieldPath: fieldTransform.field.canonicalString(), - setToServerValue: 'REQUEST_TIME' - }; - } - else if (transform instanceof ArrayUnionTransformOperation) { - return { - fieldPath: fieldTransform.field.canonicalString(), - appendMissingElements: { - values: transform.elements - } - }; - } - else if (transform instanceof ArrayRemoveTransformOperation) { - return { - fieldPath: fieldTransform.field.canonicalString(), - removeAllFromArray: { - values: transform.elements - } - }; - } - else if (transform instanceof NumericIncrementTransformOperation) { - return { - fieldPath: fieldTransform.field.canonicalString(), - increment: transform.operand - }; - } - else { - throw fail(); - } - } - function toQueryTarget(serializer, target) { - // Dissect the path into parent, collectionId, and optional key filter. - const queryTarget = { structuredQuery: {} }; - const path = target.path; - let parent; - if (target.collectionGroup !== null) { - parent = path; - queryTarget.structuredQuery.from = [ - { - collectionId: target.collectionGroup, - allDescendants: true - } - ]; - } - else { - parent = path.popLast(); - queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; - } - queryTarget.parent = toQueryPath(serializer, parent); - const where = toFilters(target.filters); - if (where) { - queryTarget.structuredQuery.where = where; - } - const orderBy = toOrder(target.orderBy); - if (orderBy) { - queryTarget.structuredQuery.orderBy = orderBy; - } - const limit = toInt32Proto(serializer, target.limit); - if (limit !== null) { - queryTarget.structuredQuery.limit = limit; - } - if (target.startAt) { - queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); - } - if (target.endAt) { - queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); - } - return { queryTarget, parent }; - } - function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { - const { queryTarget, parent } = toQueryTarget(serializer, target); - const aliasMap = {}; - const aggregations = []; - let aggregationNum = 0; - aggregates.forEach(aggregate => { - // Map all client-side aliases to a unique short-form - // alias. This avoids issues with client-side aliases that - // exceed the 1500-byte string size limit. - const serverAlias = `aggregate_${aggregationNum++}`; - aliasMap[serverAlias] = aggregate.alias; - if (aggregate.aggregateType === 'count') { - aggregations.push({ - alias: serverAlias, - count: {} - }); - } - else if (aggregate.aggregateType === 'avg') { - aggregations.push({ - alias: serverAlias, - avg: { - field: toFieldPathReference(aggregate.fieldPath) - } - }); - } - else if (aggregate.aggregateType === 'sum') { - aggregations.push({ - alias: serverAlias, - sum: { - field: toFieldPathReference(aggregate.fieldPath) - } - }); - } - }); - return { - request: { - structuredAggregationQuery: { - aggregations, - structuredQuery: queryTarget.structuredQuery - }, - parent: queryTarget.parent - }, - aliasMap, - parent - }; - } - function toFilters(filters) { - if (filters.length === 0) { - return; - } - return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); - } - function toOrder(orderBys) { - if (orderBys.length === 0) { - return; - } - return orderBys.map(order => toPropertyOrder(order)); - } - function toStartAtCursor(cursor) { - return { - before: cursor.inclusive, - values: cursor.position - }; - } - function toEndAtCursor(cursor) { - return { - before: !cursor.inclusive, - values: cursor.position - }; - } - // visible for testing - function toDirection(dir) { - return DIRECTIONS[dir]; - } - // visible for testing - function toOperatorName(op) { - return OPERATORS[op]; - } - function toCompositeOperatorName(op) { - return COMPOSITE_OPERATORS[op]; - } - function toFieldPathReference(path) { - return { fieldPath: path.canonicalString() }; - } - // visible for testing - function toPropertyOrder(orderBy) { - return { - field: toFieldPathReference(orderBy.field), - direction: toDirection(orderBy.dir) - }; - } - // visible for testing - function toFilter(filter) { - if (filter instanceof FieldFilter) { - return toUnaryOrFieldFilter(filter); - } - else if (filter instanceof CompositeFilter) { - return toCompositeFilter(filter); - } - else { - return fail(); - } - } - function toCompositeFilter(filter) { - const protos = filter.getFilters().map(filter => toFilter(filter)); - if (protos.length === 1) { - return protos[0]; - } - return { - compositeFilter: { - op: toCompositeOperatorName(filter.op), - filters: protos - } - }; - } - function toUnaryOrFieldFilter(filter) { - if (filter.op === "==" /* Operator.EQUAL */) { - if (isNanValue(filter.value)) { - return { - unaryFilter: { - field: toFieldPathReference(filter.field), - op: 'IS_NAN' - } - }; - } - else if (isNullValue(filter.value)) { - return { - unaryFilter: { - field: toFieldPathReference(filter.field), - op: 'IS_NULL' - } - }; - } - } - else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { - if (isNanValue(filter.value)) { - return { - unaryFilter: { - field: toFieldPathReference(filter.field), - op: 'IS_NOT_NAN' - } - }; - } - else if (isNullValue(filter.value)) { - return { - unaryFilter: { - field: toFieldPathReference(filter.field), - op: 'IS_NOT_NULL' - } - }; - } - } - return { - fieldFilter: { - field: toFieldPathReference(filter.field), - op: toOperatorName(filter.op), - value: filter.value - } - }; - } - function toDocumentMask(fieldMask) { - const canonicalFields = []; - fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); - return { - fieldPaths: canonicalFields - }; - } - function isValidResourceName(path) { - // Resource names have at least 4 components (project ID, database ID) - return (path.length >= 4 && - path.get(0) === 'projects' && - path.get(2) === 'databases'); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - function newSerializer(databaseId) { - return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true); - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - const LOG_TAG$2 = 'ExponentialBackoff'; - /** - * Initial backoff time in milliseconds after an error. - * Set to 1s according to https://cloud.google.com/apis/design/errors. - */ - const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; - const DEFAULT_BACKOFF_FACTOR = 1.5; - /** Maximum backoff time in milliseconds */ - const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; - /** - * A helper for running delayed tasks following an exponential backoff curve - * between attempts. - * - * Each delay is made up of a "base" delay which follows the exponential - * backoff curve, and a +/- 50% "jitter" that is calculated and added to the - * base delay. This prevents clients from accidentally synchronizing their - * delays causing spikes of load to the backend. - */ - class ExponentialBackoff { - constructor( - /** - * The AsyncQueue to run backoff operations on. - */ - queue, - /** - * The ID to use when scheduling backoff operations on the AsyncQueue. - */ - timerId, - /** - * The initial delay (used as the base delay on the first retry attempt). - * Note that jitter will still be applied, so the actual delay could be as - * little as 0.5*initialDelayMs. - */ - initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, - /** - * The multiplier to use to determine the extended base delay after each - * attempt. - */ - backoffFactor = DEFAULT_BACKOFF_FACTOR, - /** - * The maximum base delay after which no further backoff is performed. - * Note that jitter will still be applied, so the actual delay could be as - * much as 1.5*maxDelayMs. - */ - maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { - this.queue = queue; - this.timerId = timerId; - this.initialDelayMs = initialDelayMs; - this.backoffFactor = backoffFactor; - this.maxDelayMs = maxDelayMs; - this.currentBaseMs = 0; - this.timerPromise = null; - /** The last backoff attempt, as epoch milliseconds. */ - this.lastAttemptTime = Date.now(); - this.reset(); - } - /** - * Resets the backoff delay. - * - * The very next backoffAndWait() will have no delay. If it is called again - * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and - * subsequent ones will increase according to the backoffFactor. - */ - reset() { - this.currentBaseMs = 0; - } - /** - * Resets the backoff delay to the maximum delay (e.g. for use after a - * RESOURCE_EXHAUSTED error). - */ - resetToMax() { - this.currentBaseMs = this.maxDelayMs; - } - /** - * Returns a promise that resolves after currentDelayMs, and increases the - * delay for any subsequent attempts. If there was a pending backoff operation - * already, it will be canceled. - */ - backoffAndRun(op) { - // Cancel any pending backoff operation. - this.cancel(); - // First schedule using the current base (which may be 0 and should be - // honored as such). - const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); - // Guard against lastAttemptTime being in the future due to a clock change. - const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); - // Guard against the backoff delay already being past. - const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); - if (remainingDelayMs > 0) { - logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` + - `(base delay: ${this.currentBaseMs} ms, ` + - `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + - `last attempt: ${delaySoFarMs} ms ago)`); - } - this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { - this.lastAttemptTime = Date.now(); - return op(); - }); - // Apply backoff factor to determine next delay and ensure it is within - // bounds. - this.currentBaseMs *= this.backoffFactor; - if (this.currentBaseMs < this.initialDelayMs) { - this.currentBaseMs = this.initialDelayMs; - } - if (this.currentBaseMs > this.maxDelayMs) { - this.currentBaseMs = this.maxDelayMs; - } - } - skipBackoff() { - if (this.timerPromise !== null) { - this.timerPromise.skipDelay(); - this.timerPromise = null; - } - } - cancel() { - if (this.timerPromise !== null) { - this.timerPromise.cancel(); - this.timerPromise = null; - } - } - /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ - jitterDelayMs() { - return (Math.random() - 0.5) * this.currentBaseMs; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Datastore and its related methods are a wrapper around the external Google - * Cloud Datastore grpc API, which provides an interface that is more convenient - * for the rest of the client SDK architecture to consume. - */ - class Datastore { - } - /** - * An implementation of Datastore that exposes additional state for internal - * consumption. - */ - class DatastoreImpl extends Datastore { - constructor(authCredentials, appCheckCredentials, connection, serializer) { - super(); - this.authCredentials = authCredentials; - this.appCheckCredentials = appCheckCredentials; - this.connection = connection; - this.serializer = serializer; - this.terminated = false; - } - verifyInitialized() { - if (this.terminated) { - throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); - } - } - /** Invokes the provided RPC with auth and AppCheck tokens. */ - invokeRPC(rpcName, databaseId, resourcePath, request) { - this.verifyInitialized(); - return Promise.all([ - this.authCredentials.getToken(), - this.appCheckCredentials.getToken() - ]) - .then(([authToken, appCheckToken]) => { - return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); - }) - .catch((error) => { - if (error.name === 'FirebaseError') { - if (error.code === Code.UNAUTHENTICATED) { - this.authCredentials.invalidateToken(); - this.appCheckCredentials.invalidateToken(); - } - throw error; - } - else { - throw new FirestoreError(Code.UNKNOWN, error.toString()); - } - }); - } - /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ - invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { - this.verifyInitialized(); - return Promise.all([ - this.authCredentials.getToken(), - this.appCheckCredentials.getToken() - ]) - .then(([authToken, appCheckToken]) => { - return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); - }) - .catch((error) => { - if (error.name === 'FirebaseError') { - if (error.code === Code.UNAUTHENTICATED) { - this.authCredentials.invalidateToken(); - this.appCheckCredentials.invalidateToken(); - } - throw error; - } - else { - throw new FirestoreError(Code.UNKNOWN, error.toString()); - } - }); - } - terminate() { - this.terminated = true; - this.connection.terminate(); - } - } - // TODO(firestorexp): Make sure there is only one Datastore instance per - // firestore-exp client. - function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { - return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); - } - async function invokeCommitRpc(datastore, mutations) { - const datastoreImpl = debugCast(datastore); - const request = { - writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) - }; - await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); - } - async function invokeBatchGetDocumentsRpc(datastore, keys) { - const datastoreImpl = debugCast(datastore); - const request = { - documents: keys.map(k => toName(datastoreImpl.serializer, k)) - }; - const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); - const docs = new Map(); - response.forEach(proto => { - const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); - docs.set(doc.key.toString(), doc); - }); - const result = []; - keys.forEach(key => { - const doc = docs.get(key.toString()); - hardAssert(!!doc); - result.push(doc); - }); - return result; - } - async function invokeRunQueryRpc(datastore, query) { - const datastoreImpl = debugCast(datastore); - const { queryTarget, parent } = toQueryTarget(datastoreImpl.serializer, queryToTarget(query)); - const response = await datastoreImpl.invokeStreamingRPC('RunQuery', datastoreImpl.serializer.databaseId, parent, { - structuredQuery: queryTarget.structuredQuery - }); - return (response - // Omit RunQueryResponses that only contain readTimes. - .filter(proto => !!proto.document) - .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined))); - } - async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { - var _a; - const datastoreImpl = debugCast(datastore); - const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); - if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { - delete request.parent; - } - const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, - /*expectedResponseCount=*/ 1); - // Omit RunAggregationQueryResponse that only contain readTimes. - const filteredResult = response.filter(proto => !!proto.result); - hardAssert(filteredResult.length === 1); - // Remap the short-form aliases that were sent to the server - // to the client-side aliases. Users will access the results - // using the client-side alias. - const unmappedAggregateFields = (_a = filteredResult[0].result) === null || _a === void 0 ? void 0 : _a.aggregateFields; - const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { - accumulator[aliasMap[key]] = unmappedAggregateFields[key]; - return accumulator; - }, {}); - return remappedFields; - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - const LOG_TAG$1 = 'ComponentProvider'; - /** - * An instance map that ensures only one Datastore exists per Firestore - * instance. - */ - const datastoreInstances = new Map(); - /** - * Returns an initialized and started Datastore for the given Firestore - * instance. Callers must invoke removeComponents() when the Firestore - * instance is terminated. - */ - function getDatastore(firestore) { - if (firestore._terminated) { - throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); - } - if (!datastoreInstances.has(firestore)) { - logDebug(LOG_TAG$1, 'Initializing Datastore'); - const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings()); - const connection = newConnection(databaseInfo); - const serializer = newSerializer(firestore._databaseId); - const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer); - datastoreInstances.set(firestore, datastore); - } - return datastoreInstances.get(firestore); - } - /** - * Removes all components associated with the provided instance. Must be called - * when the `Firestore` instance is terminated. - */ - function removeComponents(firestore) { - const datastore = datastoreInstances.get(firestore); - if (datastore) { - logDebug(LOG_TAG$1, 'Removing Datastore'); - datastoreInstances.delete(firestore); - datastore.terminate(); - } - } - function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { - return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams); - } - - /** - * @license - * Copyright 2018 Google LLC - * - * 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. - */ - const LRU_COLLECTION_DISABLED = -1; - const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** Verifies whether `e` is an IndexedDbTransactionError. */ - function isIndexedDbTransactionError(e) { - // Use name equality, as instanceof checks on errors don't work with errors - // that wrap other errors. - return e.name === 'IndexedDbTransactionError'; - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - // settings() defaults: - const DEFAULT_HOST = 'firestore.googleapis.com'; - const DEFAULT_SSL = true; - // The minimum long-polling timeout is hardcoded on the server. The value here - // should be kept in sync with the value used by the server, as the server will - // silently ignore a value below the minimum and fall back to the default. - // Googlers see b/266868871 for relevant discussion. - const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; - // No maximum long-polling timeout is configured in the server, and defaults to - // 30 seconds, which is what Watch appears to use. - // Googlers see b/266868871 for relevant discussion. - const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; - // Whether long-polling auto-detected is enabled by default. - const DEFAULT_AUTO_DETECT_LONG_POLLING = true; - /** - * A concrete type describing all the values that can be applied via a - * user-supplied `FirestoreSettings` object. This is a separate type so that - * defaults can be supplied and the value can be checked for equality. - */ - class FirestoreSettingsImpl { - constructor(settings) { - var _a, _b; - if (settings.host === undefined) { - if (settings.ssl !== undefined) { - throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); - } - this.host = DEFAULT_HOST; - this.ssl = DEFAULT_SSL; - } - else { - this.host = settings.host; - this.ssl = (_a = settings.ssl) !== null && _a !== void 0 ? _a : DEFAULT_SSL; - } - this.credentials = settings.credentials; - this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; - this.localCache = settings.localCache; - if (settings.cacheSizeBytes === undefined) { - this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; - } - else { - if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && - settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); - } - else { - this.cacheSizeBytes = settings.cacheSizeBytes; - } - } - validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); - this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; - if (this.experimentalForceLongPolling) { - this.experimentalAutoDetectLongPolling = false; - } - else if (settings.experimentalAutoDetectLongPolling === undefined) { - this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; - } - else { - // For backwards compatibility, coerce the value to boolean even though - // the TypeScript compiler has narrowed the type to boolean already. - // noinspection PointlessBooleanExpressionJS - this.experimentalAutoDetectLongPolling = - !!settings.experimentalAutoDetectLongPolling; - } - this.experimentalLongPollingOptions = cloneLongPollingOptions((_b = settings.experimentalLongPollingOptions) !== null && _b !== void 0 ? _b : {}); - validateLongPollingOptions(this.experimentalLongPollingOptions); - this.useFetchStreams = !!settings.useFetchStreams; - } - isEqual(other) { - return (this.host === other.host && - this.ssl === other.ssl && - this.credentials === other.credentials && - this.cacheSizeBytes === other.cacheSizeBytes && - this.experimentalForceLongPolling === - other.experimentalForceLongPolling && - this.experimentalAutoDetectLongPolling === - other.experimentalAutoDetectLongPolling && - longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && - this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && - this.useFetchStreams === other.useFetchStreams); - } - } - function validateLongPollingOptions(options) { - if (options.timeoutSeconds !== undefined) { - if (isNaN(options.timeoutSeconds)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + - `${options.timeoutSeconds} (must not be NaN)`); - } - if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + - `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); - } - if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + - `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); - } - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * The Cloud Firestore service interface. - * - * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. - */ - class Firestore { - /** @hideconstructor */ - constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { - this._authCredentials = _authCredentials; - this._appCheckCredentials = _appCheckCredentials; - this._databaseId = _databaseId; - this._app = _app; - /** - * Whether it's a Firestore or Firestore Lite instance. - */ - this.type = 'firestore-lite'; - this._persistenceKey = '(lite)'; - this._settings = new FirestoreSettingsImpl({}); - this._settingsFrozen = false; - // A task that is assigned when the terminate() is invoked and resolved when - // all components have shut down. Otherwise, Firestore is not terminated, - // which can mean either the FirestoreClient is in the process of starting, - // or restarting. - this._terminateTask = 'notTerminated'; - } - /** - * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service - * instance. - */ - get app() { - if (!this._app) { - throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + - 'not available'); - } - return this._app; - } - get _initialized() { - return this._settingsFrozen; - } - get _terminated() { - return this._terminateTask !== 'notTerminated'; - } - _setSettings(settings) { - if (this._settingsFrozen) { - throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + - 'be changed. You can only modify settings before calling any other ' + - 'methods on a Firestore object.'); - } - this._settings = new FirestoreSettingsImpl(settings); - if (settings.credentials !== undefined) { - this._authCredentials = makeAuthCredentialsProvider(settings.credentials); - } - } - _getSettings() { - return this._settings; - } - _freezeSettings() { - this._settingsFrozen = true; - return this._settings; - } - _delete() { - // The `_terminateTask` must be assigned future that completes when - // terminate is complete. The existence of this future puts SDK in state - // that will not accept further API interaction. - if (this._terminateTask === 'notTerminated') { - this._terminateTask = this._terminate(); - } - return this._terminateTask; - } - async _restart() { - // The `_terminateTask` must equal 'notTerminated' after restart to - // signal that client is in a state that accepts API calls. - if (this._terminateTask === 'notTerminated') { - await this._terminate(); - } - else { - this._terminateTask = 'notTerminated'; - } - } - /** Returns a JSON-serializable representation of this `Firestore` instance. */ - toJSON() { - return { - app: this._app, - databaseId: this._databaseId, - settings: this._settings - }; - } - /** - * Terminates all components used by this client. Subclasses can override - * this method to clean up their own dependencies, but must also call this - * method. - * - * Only ever called once. - */ - _terminate() { - removeComponents(this); - return Promise.resolve(); - } - } - function initializeFirestore(app$1, settings, databaseId) { - if (!databaseId) { - databaseId = DEFAULT_DATABASE_NAME; - } - const provider = app._getProvider(app$1, 'firestore/lite'); - if (provider.isInitialized(databaseId)) { - throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.'); - } - return provider.initialize({ - options: settings, - instanceIdentifier: databaseId - }); - } - function getFirestore(appOrDatabaseId, optionalDatabaseId) { - const app$1 = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : app.getApp(); - const databaseId = typeof appOrDatabaseId === 'string' - ? appOrDatabaseId - : optionalDatabaseId || '(default)'; - const db = app._getProvider(app$1, 'firestore/lite').getImmediate({ - identifier: databaseId - }); - if (!db._initialized) { - const emulator = util.getDefaultEmulatorHostnameAndPort('firestore'); - if (emulator) { - connectFirestoreEmulator(db, ...emulator); - } - } - return db; - } - /** - * Modify this instance to communicate with the Cloud Firestore emulator. - * - * Note: This must be called before this instance has been used to do any - * operations. - * - * @param firestore - The `Firestore` instance to configure to connect to the - * emulator. - * @param host - the emulator host (ex: localhost). - * @param port - the emulator port (ex: 9000). - * @param options.mockUserToken - the mock auth token to use for unit testing - * Security Rules. - */ - function connectFirestoreEmulator(firestore, host, port, options = {}) { - var _a; - firestore = cast(firestore, Firestore); - const settings = firestore._getSettings(); - const newHostSetting = `${host}:${port}`; - if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { - logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + - 'will be used.'); - } - firestore._setSettings(Object.assign(Object.assign({}, settings), { host: newHostSetting, ssl: false })); - if (options.mockUserToken) { - let token; - let user; - if (typeof options.mockUserToken === 'string') { - token = options.mockUserToken; - user = User.MOCK_USER; - } - else { - // Let createMockUserToken validate first (catches common mistakes like - // invalid field "uid" and missing field "sub" / "user_id".) - token = util.createMockUserToken(options.mockUserToken, (_a = firestore._app) === null || _a === void 0 ? void 0 : _a.options.projectId); - const uid = options.mockUserToken.sub || options.mockUserToken.user_id; - if (!uid) { - throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); - } - user = new User(uid); - } - firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); - } - } - /** - * Terminates the provided `Firestore` instance. - * - * After calling `terminate()` only the `clearIndexedDbPersistence()` functions - * may be used. Any other function will throw a `FirestoreError`. Termination - * does not cancel any pending writes, and any promises that are awaiting a - * response from the server will not be resolved. - * - * To restart after termination, create a new instance of `Firestore` with - * {@link (getFirestore:1)}. - * - * Note: Under normal circumstances, calling `terminate()` is not required. This - * function is useful only when you want to force this instance to release all of - * its resources or in combination with {@link clearIndexedDbPersistence} to - * ensure that all local state is destroyed between test runs. - * - * @param firestore - The `Firestore` instance to terminate. - * @returns A `Promise` that is resolved when the instance has been successfully - * terminated. - */ - function terminate(firestore) { - firestore = cast(firestore, Firestore); - app._removeServiceInstance(firestore.app, 'firestore/lite'); - return firestore._delete(); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - function registerFirestore() { - setSDKVersion(`${app.SDK_VERSION}_lite`); - app._registerComponent(new component.Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => { - const app = container.getProvider('app').getImmediate(); - const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); - if (settings) { - firestoreInstance._setSettings(settings); - } - return firestoreInstance; - }, 'PUBLIC').setMultipleInstances(true)); - // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation - app.registerVersion('firestore-lite', version$1, 'node'); - app.registerVersion('firestore-lite', version$1, 'cjs2017'); - } - - /** - * @license - * Copyright 2023 Google LLC - * - * 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. - */ - /** - * Concrete implementation of the Aggregate type. - */ - class AggregateImpl { - constructor(alias, aggregateType, fieldPath) { - this.alias = alias; - this.aggregateType = aggregateType; - this.fieldPath = fieldPath; - } - } - - /** - * @license - * Copyright 2022 Google LLC - * - * 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. - */ - /** - * Represents an aggregation that can be performed by Firestore. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - class AggregateField { - /** - * Create a new AggregateField - * @param aggregateType Specifies the type of aggregation operation to perform. - * @param _internalFieldPath Optionally specifies the field that is aggregated. - * @internal - */ - constructor(aggregateType = 'count', _internalFieldPath) { - this._internalFieldPath = _internalFieldPath; - /** A type string to uniquely identify instances of this class. */ - this.type = 'AggregateField'; - this.aggregateType = aggregateType; - } - } - /** - * The results of executing an aggregation query. - */ - class AggregateQuerySnapshot { - /** @hideconstructor */ - constructor(query, _userDataWriter, _data) { - this._userDataWriter = _userDataWriter; - this._data = _data; - /** A type string to uniquely identify instances of this class. */ - this.type = 'AggregateQuerySnapshot'; - this.query = query; - } - /** - * Returns the results of the aggregations performed over the underlying - * query. - * - * The keys of the returned object will be the same as those of the - * `AggregateSpec` object specified to the aggregation method, and the values - * will be the corresponding aggregation result. - * - * @returns The results of the aggregations performed over the underlying - * query. - */ - data() { - return this._userDataWriter.convertObjectMap(this._data); - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * A `Query` refers to a query which you can read or listen to. You can also - * construct refined `Query` objects by adding filters and ordering. - */ - class Query { - // This is the lite version of the Query class in the main SDK. - /** @hideconstructor protected */ - constructor(firestore, - /** - * If provided, the `FirestoreDataConverter` associated with this instance. - */ - converter, _query) { - this.converter = converter; - this._query = _query; - /** The type of this Firestore reference. */ - this.type = 'query'; - this.firestore = firestore; - } - withConverter(converter) { - return new Query(this.firestore, converter, this._query); - } - } - /** - * A `DocumentReference` refers to a document location in a Firestore database - * and can be used to write, read, or listen to the location. The document at - * the referenced location may or may not exist. - */ - class DocumentReference { - /** @hideconstructor */ - constructor(firestore, - /** - * If provided, the `FirestoreDataConverter` associated with this instance. - */ - converter, _key) { - this.converter = converter; - this._key = _key; - /** The type of this Firestore reference. */ - this.type = 'document'; - this.firestore = firestore; - } - get _path() { - return this._key.path; - } - /** - * The document's identifier within its collection. - */ - get id() { - return this._key.path.lastSegment(); - } - /** - * A string representing the path of the referenced document (relative - * to the root of the database). - */ - get path() { - return this._key.path.canonicalString(); - } - /** - * The collection this `DocumentReference` belongs to. - */ - get parent() { - return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); - } - withConverter(converter) { - return new DocumentReference(this.firestore, converter, this._key); - } - } - /** - * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using {@link (query:1)}). - */ - class CollectionReference extends Query { - /** @hideconstructor */ - constructor(firestore, converter, _path) { - super(firestore, converter, newQueryForPath(_path)); - this._path = _path; - /** The type of this Firestore reference. */ - this.type = 'collection'; - } - /** The collection's identifier. */ - get id() { - return this._query.path.lastSegment(); - } - /** - * A string representing the path of the referenced collection (relative - * to the root of the database). - */ - get path() { - return this._query.path.canonicalString(); - } - /** - * A reference to the containing `DocumentReference` if this is a - * subcollection. If this isn't a subcollection, the reference is null. - */ - get parent() { - const parentPath = this._path.popLast(); - if (parentPath.isEmpty()) { - return null; - } - else { - return new DocumentReference(this.firestore, - /* converter= */ null, new DocumentKey(parentPath)); - } - } - withConverter(converter) { - return new CollectionReference(this.firestore, converter, this._path); - } - } - function collection(parent, path, ...pathSegments) { - parent = util.getModularInstance(parent); - validateNonEmptyArgument('collection', 'path', path); - if (parent instanceof Firestore) { - const absolutePath = ResourcePath.fromString(path, ...pathSegments); - validateCollectionPath(absolutePath); - return new CollectionReference(parent, /* converter= */ null, absolutePath); - } - else { - if (!(parent instanceof DocumentReference) && - !(parent instanceof CollectionReference)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + - 'a DocumentReference or FirebaseFirestore'); - } - const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); - validateCollectionPath(absolutePath); - return new CollectionReference(parent.firestore, - /* converter= */ null, absolutePath); - } - } - // TODO(firestorelite): Consider using ErrorFactory - - // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 - /** - * Creates and returns a new `Query` instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given `collectionId`. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param collectionId - Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * @returns The created `Query`. - */ - function collectionGroup(firestore, collectionId) { - firestore = cast(firestore, Firestore); - validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); - if (collectionId.indexOf('/') >= 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + - `collectionGroup(). Collection IDs must not contain '/'.`); - } - return new Query(firestore, - /* converter= */ null, newQueryForCollectionGroup(collectionId)); - } - function doc(parent, path, ...pathSegments) { - parent = util.getModularInstance(parent); - // We allow omission of 'pathString' but explicitly prohibit passing in both - // 'undefined' and 'null'. - if (arguments.length === 1) { - path = AutoId.newId(); - } - validateNonEmptyArgument('doc', 'path', path); - if (parent instanceof Firestore) { - const absolutePath = ResourcePath.fromString(path, ...pathSegments); - validateDocumentPath(absolutePath); - return new DocumentReference(parent, - /* converter= */ null, new DocumentKey(absolutePath)); - } - else { - if (!(parent instanceof DocumentReference) && - !(parent instanceof CollectionReference)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + - 'a DocumentReference or FirebaseFirestore'); - } - const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); - validateDocumentPath(absolutePath); - return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); - } - } - /** - * Returns true if the provided references are equal. - * - * @param left - A reference to compare. - * @param right - A reference to compare. - * @returns true if the references point to the same location in the same - * Firestore database. - */ - function refEqual(left, right) { - left = util.getModularInstance(left); - right = util.getModularInstance(right); - if ((left instanceof DocumentReference || - left instanceof CollectionReference) && - (right instanceof DocumentReference || right instanceof CollectionReference)) { - return (left.firestore === right.firestore && - left.path === right.path && - left.converter === right.converter); - } - return false; - } - /** - * Returns true if the provided queries point to the same collection and apply - * the same constraints. - * - * @param left - A `Query` to compare. - * @param right - A `Query` to compare. - * @returns true if the references point to the same location in the same - * Firestore database. - */ - function queryEqual(left, right) { - left = util.getModularInstance(left); - right = util.getModularInstance(right); - if (left instanceof Query && right instanceof Query) { - return (left.firestore === right.firestore && - queryEquals(left._query, right._query) && - left.converter === right.converter); - } - return false; - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * An immutable object representing an array of bytes. - */ - class Bytes { - /** @hideconstructor */ - constructor(byteString) { - this._byteString = byteString; - } - /** - * Creates a new `Bytes` object from the given Base64 string, converting it to - * bytes. - * - * @param base64 - The Base64 string used to create the `Bytes` object. - */ - static fromBase64String(base64) { - try { - return new Bytes(ByteString.fromBase64String(base64)); - } - catch (e) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); - } - } - /** - * Creates a new `Bytes` object from the given Uint8Array. - * - * @param array - The Uint8Array used to create the `Bytes` object. - */ - static fromUint8Array(array) { - return new Bytes(ByteString.fromUint8Array(array)); - } - /** - * Returns the underlying bytes as a Base64-encoded string. - * - * @returns The Base64-encoded string created from the `Bytes` object. - */ - toBase64() { - return this._byteString.toBase64(); - } - /** - * Returns the underlying bytes in a new `Uint8Array`. - * - * @returns The Uint8Array created from the `Bytes` object. - */ - toUint8Array() { - return this._byteString.toUint8Array(); - } - /** - * Returns a string representation of the `Bytes` object. - * - * @returns A string representation of the `Bytes` object. - */ - toString() { - return 'Bytes(base64: ' + this.toBase64() + ')'; - } - /** - * Returns true if this `Bytes` object is equal to the provided one. - * - * @param other - The `Bytes` object to compare against. - * @returns true if this `Bytes` object is equal to the provided one. - */ - isEqual(other) { - return this._byteString.isEqual(other._byteString); - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * A `FieldPath` refers to a field in a document. The path may consist of a - * single field name (referring to a top-level field in the document), or a - * list of field names (referring to a nested field in the document). - * - * Create a `FieldPath` by providing field names. If more than one field - * name is provided, the path will point to a nested field in a document. - */ - class FieldPath { - /** - * Creates a `FieldPath` from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param fieldNames - A list of field names. - */ - constructor(...fieldNames) { - for (let i = 0; i < fieldNames.length; ++i) { - if (fieldNames[i].length === 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + - 'Field names must not be empty.'); - } - } - this._internalPath = new FieldPath$1(fieldNames); - } - /** - * Returns true if this `FieldPath` is equal to the provided one. - * - * @param other - The `FieldPath` to compare against. - * @returns true if this `FieldPath` is equal to the provided one. - */ - isEqual(other) { - return this._internalPath.isEqual(other._internalPath); - } - } - /** - * Returns a special sentinel `FieldPath` to refer to the ID of a document. - * It can be used in queries to sort or filter by the document ID. - */ - function documentId() { - return new FieldPath(DOCUMENT_KEY_NAME); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Sentinel values that can be used when writing document fields with `set()` - * or `update()`. - */ - class FieldValue { - /** - * @param _methodName - The public API endpoint that returns this class. - * @hideconstructor - */ - constructor(_methodName) { - this._methodName = _methodName; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * An immutable object representing a geographic location in Firestore. The - * location is represented as latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ - class GeoPoint { - /** - * Creates a new immutable `GeoPoint` object with the provided latitude and - * longitude values. - * @param latitude - The latitude as number between -90 and 90. - * @param longitude - The longitude as number between -180 and 180. - */ - constructor(latitude, longitude) { - if (!isFinite(latitude) || latitude < -90 || latitude > 90) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); - } - if (!isFinite(longitude) || longitude < -180 || longitude > 180) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); - } - this._lat = latitude; - this._long = longitude; - } - /** - * The latitude of this `GeoPoint` instance. - */ - get latitude() { - return this._lat; - } - /** - * The longitude of this `GeoPoint` instance. - */ - get longitude() { - return this._long; - } - /** - * Returns true if this `GeoPoint` is equal to the provided one. - * - * @param other - The `GeoPoint` to compare against. - * @returns true if this `GeoPoint` is equal to the provided one. - */ - isEqual(other) { - return this._lat === other._lat && this._long === other._long; - } - /** Returns a JSON-serializable representation of this GeoPoint. */ - toJSON() { - return { latitude: this._lat, longitude: this._long }; - } - /** - * Actually private to JS consumers of our API, so this function is prefixed - * with an underscore. - */ - _compareTo(other) { - return (primitiveComparator(this._lat, other._lat) || - primitiveComparator(this._long, other._long)); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Verifies equality for an array of primitives. - * - * @private - * @internal - * @param left Array of primitives. - * @param right Array of primitives. - * @return True if arrays are equal. - */ - function isPrimitiveArrayEqual(left, right) { - if (left.length !== right.length) { - return false; - } - for (let i = 0; i < left.length; ++i) { - if (left[i] !== right[i]) { - return false; - } - } - return true; - } - - /** - * @license - * Copyright 2024 Google LLC - * - * 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. - */ - /** - * Represents a vector type in Firestore documents. - * Create an instance with {@link FieldValue.vector}. - * - * @class VectorValue - */ - class VectorValue { - /** - * @private - * @internal - */ - constructor(values) { - // Making a copy of the parameter. - this._values = (values || []).map(n => n); - } - /** - * Returns a copy of the raw number array form of the vector. - */ - toArray() { - return this._values.map(n => n); - } - /** - * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. - */ - isEqual(other) { - return isPrimitiveArrayEqual(this._values, other._values); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - const RESERVED_FIELD_REGEX = /^__.*__$/; - /** The result of parsing document data (e.g. for a setData call). */ - class ParsedSetData { - constructor(data, fieldMask, fieldTransforms) { - this.data = data; - this.fieldMask = fieldMask; - this.fieldTransforms = fieldTransforms; - } - toMutation(key, precondition) { - if (this.fieldMask !== null) { - return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); - } - else { - return new SetMutation(key, this.data, precondition, this.fieldTransforms); - } - } - } - /** The result of parsing "update" data (i.e. for an updateData call). */ - class ParsedUpdateData { - constructor(data, - // The fieldMask does not include document transforms. - fieldMask, fieldTransforms) { - this.data = data; - this.fieldMask = fieldMask; - this.fieldTransforms = fieldTransforms; - } - toMutation(key, precondition) { - return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); - } - } - function isWrite(dataSource) { - switch (dataSource) { - case 0 /* UserDataSource.Set */: // fall through - case 2 /* UserDataSource.MergeSet */: // fall through - case 1 /* UserDataSource.Update */: - return true; - case 3 /* UserDataSource.Argument */: - case 4 /* UserDataSource.ArrayArgument */: - return false; - default: - throw fail(); - } - } - /** A "context" object passed around while parsing user data. */ - class ParseContextImpl { - /** - * Initializes a ParseContext with the given source and path. - * - * @param settings - The settings for the parser. - * @param databaseId - The database ID of the Firestore instance. - * @param serializer - The serializer to use to generate the Value proto. - * @param ignoreUndefinedProperties - Whether to ignore undefined properties - * rather than throw. - * @param fieldTransforms - A mutable list of field transforms encountered - * while parsing the data. - * @param fieldMask - A mutable list of field paths encountered while parsing - * the data. - * - * TODO(b/34871131): We don't support array paths right now, so path can be - * null to indicate the context represents any location within an array (in - * which case certain features will not work and errors will be somewhat - * compromised). - */ - constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { - this.settings = settings; - this.databaseId = databaseId; - this.serializer = serializer; - this.ignoreUndefinedProperties = ignoreUndefinedProperties; - // Minor hack: If fieldTransforms is undefined, we assume this is an - // external call and we need to validate the entire path. - if (fieldTransforms === undefined) { - this.validatePath(); - } - this.fieldTransforms = fieldTransforms || []; - this.fieldMask = fieldMask || []; - } - get path() { - return this.settings.path; - } - get dataSource() { - return this.settings.dataSource; - } - /** Returns a new context with the specified settings overwritten. */ - contextWith(configuration) { - return new ParseContextImpl(Object.assign(Object.assign({}, this.settings), configuration), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); - } - childContextForField(field) { - var _a; - const childPath = (_a = this.path) === null || _a === void 0 ? void 0 : _a.child(field); - const context = this.contextWith({ path: childPath, arrayElement: false }); - context.validatePathSegment(field); - return context; - } - childContextForFieldPath(field) { - var _a; - const childPath = (_a = this.path) === null || _a === void 0 ? void 0 : _a.child(field); - const context = this.contextWith({ path: childPath, arrayElement: false }); - context.validatePath(); - return context; - } - childContextForArray(index) { - // TODO(b/34871131): We don't support array paths right now; so make path - // undefined. - return this.contextWith({ path: undefined, arrayElement: true }); - } - createError(reason) { - return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); - } - /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ - contains(fieldPath) { - return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || - this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); - } - validatePath() { - // TODO(b/34871131): Remove null check once we have proper paths for fields - // within arrays. - if (!this.path) { - return; - } - for (let i = 0; i < this.path.length; i++) { - this.validatePathSegment(this.path.get(i)); - } - } - validatePathSegment(segment) { - if (segment.length === 0) { - throw this.createError('Document fields must not be empty'); - } - if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { - throw this.createError('Document fields cannot begin and end with "__"'); - } - } - } - /** - * Helper for parsing raw user input (provided via the API) into internal model - * classes. - */ - class UserDataReader { - constructor(databaseId, ignoreUndefinedProperties, serializer) { - this.databaseId = databaseId; - this.ignoreUndefinedProperties = ignoreUndefinedProperties; - this.serializer = serializer || newSerializer(databaseId); - } - /** Creates a new top-level parse context. */ - createContext(dataSource, methodName, targetDoc, hasConverter = false) { - return new ParseContextImpl({ - dataSource, - methodName, - targetDoc, - path: FieldPath$1.emptyPath(), - arrayElement: false, - hasConverter - }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); - } - } - function newUserDataReader(firestore) { - const settings = firestore._freezeSettings(); - const serializer = newSerializer(firestore._databaseId); - return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); - } - /** Parse document data from a set() call. */ - function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { - const context = userDataReader.createContext(options.merge || options.mergeFields - ? 2 /* UserDataSource.MergeSet */ - : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); - validatePlainObject('Data must be an object, but it was:', context, input); - const updateData = parseObject(input, context); - let fieldMask; - let fieldTransforms; - if (options.merge) { - fieldMask = new FieldMask(context.fieldMask); - fieldTransforms = context.fieldTransforms; - } - else if (options.mergeFields) { - const validatedFieldPaths = []; - for (const stringOrFieldPath of options.mergeFields) { - const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); - if (!context.contains(fieldPath)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); - } - if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { - validatedFieldPaths.push(fieldPath); - } - } - fieldMask = new FieldMask(validatedFieldPaths); - fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); - } - else { - fieldMask = null; - fieldTransforms = context.fieldTransforms; - } - return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); - } - class DeleteFieldValueImpl extends FieldValue { - _toFieldTransform(context) { - if (context.dataSource === 2 /* UserDataSource.MergeSet */) { - // No transform to add for a delete, but we need to add it to our - // fieldMask so it gets deleted. - context.fieldMask.push(context.path); - } - else if (context.dataSource === 1 /* UserDataSource.Update */) { - throw context.createError(`${this._methodName}() can only appear at the top level ` + - 'of your update data'); - } - else { - // We shouldn't encounter delete sentinels for queries or non-merge set() calls. - throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + - '{merge:true}'); - } - return null; - } - isEqual(other) { - return other instanceof DeleteFieldValueImpl; - } - } - /** - * Creates a child context for parsing SerializableFieldValues. - * - * This is different than calling `ParseContext.contextWith` because it keeps - * the fieldTransforms and fieldMask separate. - * - * The created context has its `dataSource` set to `UserDataSource.Argument`. - * Although these values are used with writes, any elements in these FieldValues - * are not considered writes since they cannot contain any FieldValue sentinels, - * etc. - * - * @param fieldValue - The sentinel FieldValue for which to create a child - * context. - * @param context - The parent context. - * @param arrayElement - Whether or not the FieldValue has an array. - */ - function createSentinelChildContext(fieldValue, context, arrayElement) { - return new ParseContextImpl({ - dataSource: 3 /* UserDataSource.Argument */, - targetDoc: context.settings.targetDoc, - methodName: fieldValue._methodName, - arrayElement - }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); - } - class ServerTimestampFieldValueImpl extends FieldValue { - _toFieldTransform(context) { - return new FieldTransform(context.path, new ServerTimestampTransform()); - } - isEqual(other) { - return other instanceof ServerTimestampFieldValueImpl; - } - } - class ArrayUnionFieldValueImpl extends FieldValue { - constructor(methodName, _elements) { - super(methodName); - this._elements = _elements; - } - _toFieldTransform(context) { - const parseContext = createSentinelChildContext(this, context, - /*array=*/ true); - const parsedElements = this._elements.map(element => parseData(element, parseContext)); - const arrayUnion = new ArrayUnionTransformOperation(parsedElements); - return new FieldTransform(context.path, arrayUnion); - } - isEqual(other) { - return (other instanceof ArrayUnionFieldValueImpl && - util.deepEqual(this._elements, other._elements)); - } - } - class ArrayRemoveFieldValueImpl extends FieldValue { - constructor(methodName, _elements) { - super(methodName); - this._elements = _elements; - } - _toFieldTransform(context) { - const parseContext = createSentinelChildContext(this, context, - /*array=*/ true); - const parsedElements = this._elements.map(element => parseData(element, parseContext)); - const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); - return new FieldTransform(context.path, arrayUnion); - } - isEqual(other) { - return (other instanceof ArrayRemoveFieldValueImpl && - util.deepEqual(this._elements, other._elements)); - } - } - class NumericIncrementFieldValueImpl extends FieldValue { - constructor(methodName, _operand) { - super(methodName); - this._operand = _operand; - } - _toFieldTransform(context) { - const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); - return new FieldTransform(context.path, numericIncrement); - } - isEqual(other) { - return (other instanceof NumericIncrementFieldValueImpl && - this._operand === other._operand); - } - } - /** Parse update data from an update() call. */ - function parseUpdateData(userDataReader, methodName, targetDoc, input) { - const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); - validatePlainObject('Data must be an object, but it was:', context, input); - const fieldMaskPaths = []; - const updateData = ObjectValue.empty(); - forEach(input, (key, value) => { - const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - value = util.getModularInstance(value); - const childContext = context.childContextForFieldPath(path); - if (value instanceof DeleteFieldValueImpl) { - // Add it to the field mask, but don't add anything to updateData. - fieldMaskPaths.push(path); - } - else { - const parsedValue = parseData(value, childContext); - if (parsedValue != null) { - fieldMaskPaths.push(path); - updateData.set(path, parsedValue); - } - } - }); - const mask = new FieldMask(fieldMaskPaths); - return new ParsedUpdateData(updateData, mask, context.fieldTransforms); - } - /** Parse update data from a list of field/value arguments. */ - function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { - const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); - const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; - const values = [value]; - if (moreFieldsAndValues.length % 2 !== 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + - 'of arguments that alternate between field names and values.'); - } - for (let i = 0; i < moreFieldsAndValues.length; i += 2) { - keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); - values.push(moreFieldsAndValues[i + 1]); - } - const fieldMaskPaths = []; - const updateData = ObjectValue.empty(); - // We iterate in reverse order to pick the last value for a field if the - // user specified the field multiple times. - for (let i = keys.length - 1; i >= 0; --i) { - if (!fieldMaskContains(fieldMaskPaths, keys[i])) { - const path = keys[i]; - let value = values[i]; - // For Compat types, we have to "extract" the underlying types before - // performing validation. - value = util.getModularInstance(value); - const childContext = context.childContextForFieldPath(path); - if (value instanceof DeleteFieldValueImpl) { - // Add it to the field mask, but don't add anything to updateData. - fieldMaskPaths.push(path); - } - else { - const parsedValue = parseData(value, childContext); - if (parsedValue != null) { - fieldMaskPaths.push(path); - updateData.set(path, parsedValue); - } - } - } - } - const mask = new FieldMask(fieldMaskPaths); - return new ParsedUpdateData(updateData, mask, context.fieldTransforms); - } - /** - * Parse a "query value" (e.g. value in a where filter or a value in a cursor - * bound). - * - * @param allowArrays - Whether the query value is an array that may directly - * contain additional arrays (e.g. the operand of an `in` query). - */ - function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { - const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); - const parsed = parseData(input, context); - return parsed; - } - /** - * Parses user data to Protobuf Values. - * - * @param input - Data to be parsed. - * @param context - A context object representing the current path being parsed, - * the source of the data being parsed, etc. - * @returns The parsed value, or null if the value was a FieldValue sentinel - * that should not be included in the resulting parsed data. - */ - function parseData(input, context) { - // Unwrap the API type from the Compat SDK. This will return the API type - // from firestore-exp. - input = util.getModularInstance(input); - if (looksLikeJsonObject(input)) { - validatePlainObject('Unsupported field value:', context, input); - return parseObject(input, context); - } - else if (input instanceof FieldValue) { - // FieldValues usually parse into transforms (except deleteField()) - // in which case we do not want to include this field in our parsed data - // (as doing so will overwrite the field directly prior to the transform - // trying to transform it). So we don't add this location to - // context.fieldMask and we return null as our parsing result. - parseSentinelFieldValue(input, context); - return null; - } - else if (input === undefined && context.ignoreUndefinedProperties) { - // If the input is undefined it can never participate in the fieldMask, so - // don't handle this below. If `ignoreUndefinedProperties` is false, - // `parseScalarValue` will reject an undefined value. - return null; - } - else { - // If context.path is null we are inside an array and we don't support - // field mask paths more granular than the top-level array. - if (context.path) { - context.fieldMask.push(context.path); - } - if (input instanceof Array) { - // TODO(b/34871131): Include the path containing the array in the error - // message. - // In the case of IN queries, the parsed data is an array (representing - // the set of values to be included for the IN query) that may directly - // contain additional arrays (each representing an individual field - // value), so we disable this validation. - if (context.settings.arrayElement && - context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { - throw context.createError('Nested arrays are not supported'); - } - return parseArray(input, context); - } - else { - return parseScalarValue(input, context); - } - } - } - function parseObject(obj, context) { - const fields = {}; - if (isEmpty(obj)) { - // If we encounter an empty object, we explicitly add it to the update - // mask to ensure that the server creates a map entry. - if (context.path && context.path.length > 0) { - context.fieldMask.push(context.path); - } - } - else { - forEach(obj, (key, val) => { - const parsedValue = parseData(val, context.childContextForField(key)); - if (parsedValue != null) { - fields[key] = parsedValue; - } - }); - } - return { mapValue: { fields } }; - } - function parseArray(array, context) { - const values = []; - let entryIndex = 0; - for (const entry of array) { - let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); - if (parsedEntry == null) { - // Just include nulls in the array for fields being replaced with a - // sentinel. - parsedEntry = { nullValue: 'NULL_VALUE' }; - } - values.push(parsedEntry); - entryIndex++; - } - return { arrayValue: { values } }; - } - /** - * "Parses" the provided FieldValueImpl, adding any necessary transforms to - * context.fieldTransforms. - */ - function parseSentinelFieldValue(value, context) { - // Sentinels are only supported with writes, and not within arrays. - if (!isWrite(context.dataSource)) { - throw context.createError(`${value._methodName}() can only be used with update() and set()`); - } - if (!context.path) { - throw context.createError(`${value._methodName}() is not currently supported inside arrays`); - } - const fieldTransform = value._toFieldTransform(context); - if (fieldTransform) { - context.fieldTransforms.push(fieldTransform); - } - } - /** - * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) - * - * @returns The parsed value - */ - function parseScalarValue(value, context) { - value = util.getModularInstance(value); - if (value === null) { - return { nullValue: 'NULL_VALUE' }; - } - else if (typeof value === 'number') { - return toNumber(context.serializer, value); - } - else if (typeof value === 'boolean') { - return { booleanValue: value }; - } - else if (typeof value === 'string') { - return { stringValue: value }; - } - else if (value instanceof Date) { - const timestamp = Timestamp.fromDate(value); - return { - timestampValue: toTimestamp(context.serializer, timestamp) - }; - } - else if (value instanceof Timestamp) { - // Firestore backend truncates precision down to microseconds. To ensure - // offline mode works the same with regards to truncation, perform the - // truncation immediately without waiting for the backend to do that. - const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); - return { - timestampValue: toTimestamp(context.serializer, timestamp) - }; - } - else if (value instanceof GeoPoint) { - return { - geoPointValue: { - latitude: value.latitude, - longitude: value.longitude - } - }; - } - else if (value instanceof Bytes) { - return { bytesValue: toBytes(context.serializer, value._byteString) }; - } - else if (value instanceof DocumentReference) { - const thisDb = context.databaseId; - const otherDb = value.firestore._databaseId; - if (!otherDb.isEqual(thisDb)) { - throw context.createError('Document reference is for database ' + - `${otherDb.projectId}/${otherDb.database} but should be ` + - `for database ${thisDb.projectId}/${thisDb.database}`); - } - return { - referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) - }; - } - else if (value instanceof VectorValue) { - return parseVectorValue(value, context); - } - else { - throw context.createError(`Unsupported field value: ${valueDescription(value)}`); - } - } - /** - * Creates a new VectorValue proto value (using the internal format). - */ - function parseVectorValue(value, context) { - const mapValue = { - fields: { - [TYPE_KEY]: { - stringValue: VECTOR_VALUE_SENTINEL - }, - [VECTOR_MAP_VECTORS_KEY]: { - arrayValue: { - values: value.toArray().map(value => { - if (typeof value !== 'number') { - throw context.createError('VectorValues must only contain numeric values.'); - } - return toDouble(context.serializer, value); - }) - } - } - } - }; - return { mapValue }; - } - /** - * Checks whether an object looks like a JSON object that should be converted - * into a struct. Normal class/prototype instances are considered to look like - * JSON objects since they should be converted to a struct value. Arrays, Dates, - * GeoPoints, etc. are not considered to look like JSON objects since they map - * to specific FieldValue types other than ObjectValue. - */ - function looksLikeJsonObject(input) { - return (typeof input === 'object' && - input !== null && - !(input instanceof Array) && - !(input instanceof Date) && - !(input instanceof Timestamp) && - !(input instanceof GeoPoint) && - !(input instanceof Bytes) && - !(input instanceof DocumentReference) && - !(input instanceof FieldValue) && - !(input instanceof VectorValue)); - } - function validatePlainObject(message, context, input) { - if (!looksLikeJsonObject(input) || !isPlainObject(input)) { - const description = valueDescription(input); - if (description === 'an object') { - // Massage the error if it was an object. - throw context.createError(message + ' a custom object'); - } - else { - throw context.createError(message + ' ' + description); - } - } - } - /** - * Helper that calls fromDotSeparatedString() but wraps any error thrown. - */ - function fieldPathFromArgument$1(methodName, path, targetDoc) { - // If required, replace the FieldPath Compat class with the firestore-exp - // FieldPath. - path = util.getModularInstance(path); - if (path instanceof FieldPath) { - return path._internalPath; - } - else if (typeof path === 'string') { - return fieldPathFromDotSeparatedString(methodName, path); - } - else { - const message = 'Field path arguments must be of type string or '; - throw createError(message, methodName, - /* hasConverter= */ false, - /* path= */ undefined, targetDoc); - } - } - /** - * Matches any characters in a field path string that are reserved. - */ - const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); - /** - * Wraps fromDotSeparatedString with an error message about the method that - * was thrown. - * @param methodName - The publicly visible method name - * @param path - The dot-separated string form of a field path which will be - * split on dots. - * @param targetDoc - The document against which the field path will be - * evaluated. - */ - function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { - const found = path.search(FIELD_PATH_RESERVED); - if (found >= 0) { - throw createError(`Invalid field path (${path}). Paths must not contain ` + - `'~', '*', '/', '[', or ']'`, methodName, - /* hasConverter= */ false, - /* path= */ undefined, targetDoc); - } - try { - return new FieldPath(...path.split('.'))._internalPath; - } - catch (e) { - throw createError(`Invalid field path (${path}). Paths must not be empty, ` + - `begin with '.', end with '.', or contain '..'`, methodName, - /* hasConverter= */ false, - /* path= */ undefined, targetDoc); - } - } - function createError(reason, methodName, hasConverter, path, targetDoc) { - const hasPath = path && !path.isEmpty(); - const hasDocument = targetDoc !== undefined; - let message = `Function ${methodName}() called with invalid data`; - if (hasConverter) { - message += ' (via `toFirestore()`)'; - } - message += '. '; - let description = ''; - if (hasPath || hasDocument) { - description += ' (found'; - if (hasPath) { - description += ` in field ${path}`; - } - if (hasDocument) { - description += ` in document ${targetDoc}`; - } - description += ')'; - } - return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); - } - /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ - function fieldMaskContains(haystack, needle) { - return haystack.some(v => v.isEqual(needle)); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * A `DocumentSnapshot` contains data read from a document in your Firestore - * database. The data can be extracted with `.data()` or `.get()` to - * get a specific field. - * - * For a `DocumentSnapshot` that points to a non-existing document, any data - * access will return 'undefined'. You can use the `exists()` method to - * explicitly verify a document's existence. - */ - class DocumentSnapshot { - // Note: This class is stripped down version of the DocumentSnapshot in - // the legacy SDK. The changes are: - // - No support for SnapshotMetadata. - // - No support for SnapshotOptions. - /** @hideconstructor protected */ - constructor(_firestore, _userDataWriter, _key, _document, _converter) { - this._firestore = _firestore; - this._userDataWriter = _userDataWriter; - this._key = _key; - this._document = _document; - this._converter = _converter; - } - /** Property of the `DocumentSnapshot` that provides the document's ID. */ - get id() { - return this._key.path.lastSegment(); - } - /** - * The `DocumentReference` for the document included in the `DocumentSnapshot`. - */ - get ref() { - return new DocumentReference(this._firestore, this._converter, this._key); - } - /** - * Signals whether or not the document at the snapshot's location exists. - * - * @returns true if the document exists. - */ - exists() { - return this._document !== null; - } - /** - * Retrieves all fields in the document as an `Object`. Returns `undefined` if - * the document doesn't exist. - * - * @returns An `Object` containing all fields in the document or `undefined` - * if the document doesn't exist. - */ - data() { - if (!this._document) { - return undefined; - } - else if (this._converter) { - // We only want to use the converter and create a new DocumentSnapshot - // if a converter has been provided. - const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, - /* converter= */ null); - return this._converter.fromFirestore(snapshot); - } - else { - return this._userDataWriter.convertValue(this._document.data.value); - } - } - /** - * Retrieves the field specified by `fieldPath`. Returns `undefined` if the - * document or field doesn't exist. - * - * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific - * field. - * @returns The data at the specified field location or undefined if no such - * field exists in the document. - */ - // We are using `any` here to avoid an explicit cast by our users. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get(fieldPath) { - if (this._document) { - const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); - if (value !== null) { - return this._userDataWriter.convertValue(value); - } - } - return undefined; - } - } - /** - * A `QueryDocumentSnapshot` contains data read from a document in your - * Firestore database as part of a query. The document is guaranteed to exist - * and its data can be extracted with `.data()` or `.get()` to get a - * specific field. - * - * A `QueryDocumentSnapshot` offers the same API surface as a - * `DocumentSnapshot`. Since query results contain only existing documents, the - * `exists` property will always be true and `data()` will never return - * 'undefined'. - */ - class QueryDocumentSnapshot extends DocumentSnapshot { - /** - * Retrieves all fields in the document as an `Object`. - * - * @override - * @returns An `Object` containing all fields in the document. - */ - data() { - return super.data(); - } - } - /** - * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects - * representing the results of a query. The documents can be accessed as an - * array via the `docs` property or enumerated using the `forEach` method. The - * number of documents can be determined via the `empty` and `size` - * properties. - */ - class QuerySnapshot { - /** @hideconstructor */ - constructor(_query, _docs) { - this._docs = _docs; - this.query = _query; - } - /** An array of all the documents in the `QuerySnapshot`. */ - get docs() { - return [...this._docs]; - } - /** The number of documents in the `QuerySnapshot`. */ - get size() { - return this.docs.length; - } - /** True if there are no documents in the `QuerySnapshot`. */ - get empty() { - return this.docs.length === 0; - } - /** - * Enumerates all of the documents in the `QuerySnapshot`. - * - * @param callback - A callback to be called with a `QueryDocumentSnapshot` for - * each document in the snapshot. - * @param thisArg - The `this` binding for the callback. - */ - forEach(callback, thisArg) { - this._docs.forEach(callback, thisArg); - } - } - /** - * Returns true if the provided snapshots are equal. - * - * @param left - A snapshot to compare. - * @param right - A snapshot to compare. - * @returns true if the snapshots are equal. - */ - function snapshotEqual(left, right) { - left = util.getModularInstance(left); - right = util.getModularInstance(right); - if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { - return (left._firestore === right._firestore && - left._key.isEqual(right._key) && - (left._document === null - ? right._document === null - : left._document.isEqual(right._document)) && - left._converter === right._converter); - } - else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { - return (queryEqual(left.query, right.query) && - arrayEquals(left.docs, right.docs, snapshotEqual)); - } - return false; - } - /** - * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. - */ - function fieldPathFromArgument(methodName, arg) { - if (typeof arg === 'string') { - return fieldPathFromDotSeparatedString(methodName, arg); - } - else if (arg instanceof FieldPath) { - return arg._internalPath; - } - else { - return arg._delegate._internalPath; - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - function validateHasExplicitOrderByForLimitToLast(query) { - if (query.limitType === "L" /* LimitType.Last */ && - query.explicitOrderBy.length === 0) { - throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); - } - } - /** - * An `AppliableConstraint` is an abstraction of a constraint that can be applied - * to a Firestore query. - */ - class AppliableConstraint { - } - /** - * A `QueryConstraint` is used to narrow the set of documents returned by a - * Firestore query. `QueryConstraint`s are created by invoking {@link where}, - * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link - * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and - * can then be passed to {@link (query:1)} to create a new query instance that - * also contains this `QueryConstraint`. - */ - class QueryConstraint extends AppliableConstraint { - } - function query(query, queryConstraint, ...additionalQueryConstraints) { - let queryConstraints = []; - if (queryConstraint instanceof AppliableConstraint) { - queryConstraints.push(queryConstraint); - } - queryConstraints = queryConstraints.concat(additionalQueryConstraints); - validateQueryConstraintArray(queryConstraints); - for (const constraint of queryConstraints) { - query = constraint._apply(query); - } - return query; - } - /** - * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by - * a Firestore query by filtering on one or more document fields. - * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then - * be passed to {@link (query:1)} to create a new query instance that also contains - * this `QueryFieldFilterConstraint`. - */ - class QueryFieldFilterConstraint extends QueryConstraint { - /** - * @internal - */ - constructor(_field, _op, _value) { - super(); - this._field = _field; - this._op = _op; - this._value = _value; - /** The type of this query constraint */ - this.type = 'where'; - } - static _create(_field, _op, _value) { - return new QueryFieldFilterConstraint(_field, _op, _value); - } - _apply(query) { - const filter = this._parse(query); - validateNewFieldFilter(query._query, filter); - return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); - } - _parse(query) { - const reader = newUserDataReader(query.firestore); - const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); - return filter; - } - } - /** - * Creates a {@link QueryFieldFilterConstraint} that enforces that documents - * must contain the specified field and that the value should satisfy the - * relation constraint provided. - * - * @param fieldPath - The path to compare - * @param opStr - The operation string (e.g "<", "<=", "==", "<", - * "<=", "!="). - * @param value - The value for comparison - * @returns The created {@link QueryFieldFilterConstraint}. - */ - function where(fieldPath, opStr, value) { - const op = opStr; - const field = fieldPathFromArgument('where', fieldPath); - return QueryFieldFilterConstraint._create(field, op, value); - } - /** - * A `QueryCompositeFilterConstraint` is used to narrow the set of documents - * returned by a Firestore query by performing the logical OR or AND of multiple - * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. - * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or - * {@link and} and can then be passed to {@link (query:1)} to create a new query - * instance that also contains the `QueryCompositeFilterConstraint`. - */ - class QueryCompositeFilterConstraint extends AppliableConstraint { - /** - * @internal - */ - constructor( - /** The type of this query constraint */ - type, _queryConstraints) { - super(); - this.type = type; - this._queryConstraints = _queryConstraints; - } - static _create(type, _queryConstraints) { - return new QueryCompositeFilterConstraint(type, _queryConstraints); - } - _parse(query) { - const parsedFilters = this._queryConstraints - .map(queryConstraint => { - return queryConstraint._parse(query); - }) - .filter(parsedFilter => parsedFilter.getFilters().length > 0); - if (parsedFilters.length === 1) { - return parsedFilters[0]; - } - return CompositeFilter.create(parsedFilters, this._getOperator()); - } - _apply(query) { - const parsedFilter = this._parse(query); - if (parsedFilter.getFilters().length === 0) { - // Return the existing query if not adding any more filters (e.g. an empty - // composite filter). - return query; - } - validateNewFilter(query._query, parsedFilter); - return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); - } - _getQueryConstraints() { - return this._queryConstraints; - } - _getOperator() { - return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; - } - } - /** - * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of - * the given filter constraints. A disjunction filter includes a document if it - * satisfies any of the given filters. - * - * @param queryConstraints - Optional. The list of - * {@link QueryFilterConstraint}s to perform a disjunction for. These must be - * created with calls to {@link where}, {@link or}, or {@link and}. - * @returns The newly created {@link QueryCompositeFilterConstraint}. - */ - function or(...queryConstraints) { - // Only support QueryFilterConstraints - queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); - return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); - } - /** - * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of - * the given filter constraints. A conjunction filter includes a document if it - * satisfies all of the given filters. - * - * @param queryConstraints - Optional. The list of - * {@link QueryFilterConstraint}s to perform a conjunction for. These must be - * created with calls to {@link where}, {@link or}, or {@link and}. - * @returns The newly created {@link QueryCompositeFilterConstraint}. - */ - function and(...queryConstraints) { - // Only support QueryFilterConstraints - queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); - return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); - } - /** - * A `QueryOrderByConstraint` is used to sort the set of documents returned by a - * Firestore query. `QueryOrderByConstraint`s are created by invoking - * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query - * instance that also contains this `QueryOrderByConstraint`. - * - * Note: Documents that do not contain the orderBy field will not be present in - * the query result. - */ - class QueryOrderByConstraint extends QueryConstraint { - /** - * @internal - */ - constructor(_field, _direction) { - super(); - this._field = _field; - this._direction = _direction; - /** The type of this query constraint */ - this.type = 'orderBy'; - } - static _create(_field, _direction) { - return new QueryOrderByConstraint(_field, _direction); - } - _apply(query) { - const orderBy = newQueryOrderBy(query._query, this._field, this._direction); - return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); - } - } - /** - * Creates a {@link QueryOrderByConstraint} that sorts the query result by the - * specified field, optionally in descending order instead of ascending. - * - * Note: Documents that do not contain the specified field will not be present - * in the query result. - * - * @param fieldPath - The field to sort by. - * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If - * not specified, order will be ascending. - * @returns The created {@link QueryOrderByConstraint}. - */ - function orderBy(fieldPath, directionStr = 'asc') { - const direction = directionStr; - const path = fieldPathFromArgument('orderBy', fieldPath); - return QueryOrderByConstraint._create(path, direction); - } - /** - * A `QueryLimitConstraint` is used to limit the number of documents returned by - * a Firestore query. - * `QueryLimitConstraint`s are created by invoking {@link limit} or - * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new - * query instance that also contains this `QueryLimitConstraint`. - */ - class QueryLimitConstraint extends QueryConstraint { - /** - * @internal - */ - constructor( - /** The type of this query constraint */ - type, _limit, _limitType) { - super(); - this.type = type; - this._limit = _limit; - this._limitType = _limitType; - } - static _create(type, _limit, _limitType) { - return new QueryLimitConstraint(type, _limit, _limitType); - } - _apply(query) { - return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); - } - } - /** - * Creates a {@link QueryLimitConstraint} that only returns the first matching - * documents. - * - * @param limit - The maximum number of items to return. - * @returns The created {@link QueryLimitConstraint}. - */ - function limit(limit) { - validatePositiveNumber('limit', limit); - return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); - } - /** - * Creates a {@link QueryLimitConstraint} that only returns the last matching - * documents. - * - * You must specify at least one `orderBy` clause for `limitToLast` queries, - * otherwise an exception will be thrown during execution. - * - * @param limit - The maximum number of items to return. - * @returns The created {@link QueryLimitConstraint}. - */ - function limitToLast(limit) { - validatePositiveNumber('limitToLast', limit); - return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); - } - /** - * A `QueryStartAtConstraint` is used to exclude documents from the start of a - * result set returned by a Firestore query. - * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or - * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a - * new query instance that also contains this `QueryStartAtConstraint`. - */ - class QueryStartAtConstraint extends QueryConstraint { - /** - * @internal - */ - constructor( - /** The type of this query constraint */ - type, _docOrFields, _inclusive) { - super(); - this.type = type; - this._docOrFields = _docOrFields; - this._inclusive = _inclusive; - } - static _create(type, _docOrFields, _inclusive) { - return new QueryStartAtConstraint(type, _docOrFields, _inclusive); - } - _apply(query) { - const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); - return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); - } - } - function startAt(...docOrFields) { - return QueryStartAtConstraint._create('startAt', docOrFields, - /*inclusive=*/ true); - } - function startAfter(...docOrFields) { - return QueryStartAtConstraint._create('startAfter', docOrFields, - /*inclusive=*/ false); - } - /** - * A `QueryEndAtConstraint` is used to exclude documents from the end of a - * result set returned by a Firestore query. - * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or - * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new - * query instance that also contains this `QueryEndAtConstraint`. - */ - class QueryEndAtConstraint extends QueryConstraint { - /** - * @internal - */ - constructor( - /** The type of this query constraint */ - type, _docOrFields, _inclusive) { - super(); - this.type = type; - this._docOrFields = _docOrFields; - this._inclusive = _inclusive; - } - static _create(type, _docOrFields, _inclusive) { - return new QueryEndAtConstraint(type, _docOrFields, _inclusive); - } - _apply(query) { - const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); - return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); - } - } - function endBefore(...docOrFields) { - return QueryEndAtConstraint._create('endBefore', docOrFields, - /*inclusive=*/ false); - } - function endAt(...docOrFields) { - return QueryEndAtConstraint._create('endAt', docOrFields, - /*inclusive=*/ true); - } - /** Helper function to create a bound from a document or fields */ - function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { - docOrFields[0] = util.getModularInstance(docOrFields[0]); - if (docOrFields[0] instanceof DocumentSnapshot) { - return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); - } - else { - const reader = newUserDataReader(query.firestore); - return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); - } - } - function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { - let fieldValue; - if (fieldPath.isKeyField()) { - if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); - } - else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { - validateDisjunctiveFilterElements(value, op); - const referenceList = []; - for (const arrayValue of value) { - referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); - } - fieldValue = { arrayValue: { values: referenceList } }; - } - else { - fieldValue = parseDocumentIdValue(databaseId, query, value); - } - } - else { - if (op === "in" /* Operator.IN */ || - op === "not-in" /* Operator.NOT_IN */ || - op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { - validateDisjunctiveFilterElements(value, op); - } - fieldValue = parseQueryValue(dataReader, methodName, value, - /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); - } - const filter = FieldFilter.create(fieldPath, op, fieldValue); - return filter; - } - function newQueryOrderBy(query, fieldPath, direction) { - if (query.startAt !== null) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + - 'calling orderBy().'); - } - if (query.endAt !== null) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + - 'calling orderBy().'); - } - const orderBy = new OrderBy(fieldPath, direction); - return orderBy; - } - /** - * Create a `Bound` from a query and a document. - * - * Note that the `Bound` will always include the key of the document - * and so only the provided document will compare equal to the returned - * position. - * - * Will throw if the document does not contain all fields of the order by - * of the query or if any of the fields in the order by are an uncommitted - * server timestamp. - */ - function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { - if (!doc) { - throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + - `${methodName}().`); - } - const components = []; - // Because people expect to continue/end a query at the exact document - // provided, we need to use the implicit sort order rather than the explicit - // sort order, because it's guaranteed to contain the document key. That way - // the position becomes unambiguous and the query continues/ends exactly at - // the provided document. Without the key (by using the explicit sort - // orders), multiple documents could match the position, yielding duplicate - // results. - for (const orderBy of queryNormalizedOrderBy(query)) { - if (orderBy.field.isKeyField()) { - components.push(refValue(databaseId, doc.key)); - } - else { - const value = doc.data.field(orderBy.field); - if (isServerTimestamp(value)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + - 'document for which the field "' + - orderBy.field + - '" is an uncommitted server timestamp. (Since the value of ' + - 'this field is unknown, you cannot start/end a query with it.)'); - } - else if (value !== null) { - components.push(value); - } - else { - const field = orderBy.field.canonicalString(); - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + - `document for which the field '${field}' (used as the ` + - `orderBy) does not exist.`); - } - } - } - return new Bound(components, inclusive); - } - /** - * Converts a list of field values to a `Bound` for the given query. - */ - function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { - // Use explicit order by's because it has to match the query the user made - const orderBy = query.explicitOrderBy; - if (values.length > orderBy.length) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + - `The number of arguments must be less than or equal to the ` + - `number of orderBy() clauses`); - } - const components = []; - for (let i = 0; i < values.length; i++) { - const rawValue = values[i]; - const orderByComponent = orderBy[i]; - if (orderByComponent.field.isKeyField()) { - if (typeof rawValue !== 'string') { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + - `${methodName}(), but got a ${typeof rawValue}`); - } - if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + - `the value passed to ${methodName}() must be a plain document ID, but ` + - `'${rawValue}' contains a slash.`); - } - const path = query.path.child(ResourcePath.fromString(rawValue)); - if (!DocumentKey.isDocumentKey(path)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + - `documentId(), the value passed to ${methodName}() must result in a ` + - `valid document path, but '${path}' is not because it contains an odd number ` + - `of segments.`); - } - const key = new DocumentKey(path); - components.push(refValue(databaseId, key)); - } - else { - const wrapped = parseQueryValue(dataReader, methodName, rawValue); - components.push(wrapped); - } - } - return new Bound(components, inclusive); - } - /** - * Parses the given `documentIdValue` into a `ReferenceValue`, throwing - * appropriate errors if the value is anything other than a `DocumentReference` - * or `string`, or if the string is malformed. - */ - function parseDocumentIdValue(databaseId, query, documentIdValue) { - documentIdValue = util.getModularInstance(documentIdValue); - if (typeof documentIdValue === 'string') { - if (documentIdValue === '') { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + - 'must provide a valid document ID, but it was an empty string.'); - } - if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + - `documentId(), you must provide a plain document ID, but ` + - `'${documentIdValue}' contains a '/' character.`); - } - const path = query.path.child(ResourcePath.fromString(documentIdValue)); - if (!DocumentKey.isDocumentKey(path)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + - `documentId(), the value provided must result in a valid document path, ` + - `but '${path}' is not because it has an odd number of segments (${path.length}).`); - } - return refValue(databaseId, new DocumentKey(path)); - } - else if (documentIdValue instanceof DocumentReference) { - return refValue(databaseId, documentIdValue._key); - } - else { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + - `string or a DocumentReference, but it was: ` + - `${valueDescription(documentIdValue)}.`); - } - } - /** - * Validates that the value passed into a disjunctive filter satisfies all - * array requirements. - */ - function validateDisjunctiveFilterElements(value, operator) { - if (!Array.isArray(value) || value.length === 0) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + - `'${operator.toString()}' filters.`); - } - } - /** - * Given an operator, returns the set of operators that cannot be used with it. - * - * This is not a comprehensive check, and this function should be removed in the - * long term. Validations should occur in the Firestore backend. - * - * Operators in a query must adhere to the following set of rules: - * 1. Only one inequality per query. - * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. - */ - function conflictingOps(op) { - switch (op) { - case "!=" /* Operator.NOT_EQUAL */: - return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; - case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: - case "in" /* Operator.IN */: - return ["not-in" /* Operator.NOT_IN */]; - case "not-in" /* Operator.NOT_IN */: - return [ - "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, - "in" /* Operator.IN */, - "not-in" /* Operator.NOT_IN */, - "!=" /* Operator.NOT_EQUAL */ - ]; - default: - return []; - } - } - function validateNewFieldFilter(query, fieldFilter) { - const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); - if (conflictingOp !== null) { - // Special case when it's a duplicate op to give a slightly clearer error message. - if (conflictingOp === fieldFilter.op) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + - `'${fieldFilter.op.toString()}' filter.`); - } - else { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + - `with '${conflictingOp.toString()}' filters.`); - } - } - } - function validateNewFilter(query, filter) { - let testQuery = query; - const subFilters = filter.getFlattenedFilters(); - for (const subFilter of subFilters) { - validateNewFieldFilter(testQuery, subFilter); - testQuery = queryWithAddedFilter(testQuery, subFilter); - } - } - // Checks if any of the provided filter operators are included in the given list of filters and - // returns the first one that is, or null if none are. - function findOpInsideFilters(filters, operators) { - for (const filter of filters) { - for (const fieldFilter of filter.getFlattenedFilters()) { - if (operators.indexOf(fieldFilter.op) >= 0) { - return fieldFilter.op; - } - } - } - return null; - } - function validateQueryFilterConstraint(functionName, queryConstraint) { - if (!(queryConstraint instanceof QueryFieldFilterConstraint) && - !(queryConstraint instanceof QueryCompositeFilterConstraint)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); - } - } - function validateQueryConstraintArray(queryConstraint) { - const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; - const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; - if (compositeFilterCount > 1 || - (compositeFilterCount > 0 && fieldFilterCount > 0)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + - 'more than one filter at the top level. Consider nesting the multiple ' + - 'filters within an `and(...)` statement. For example: ' + - 'change `query(query, where(...), or(...))` to ' + - '`query(query, and(where(...), or(...)))`.'); - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Converts Firestore's internal types to the JavaScript types that we expose - * to the user. - * - * @internal - */ - class AbstractUserDataWriter { - convertValue(value, serverTimestampBehavior = 'none') { - switch (typeOrder(value)) { - case 0 /* TypeOrder.NullValue */: - return null; - case 1 /* TypeOrder.BooleanValue */: - return value.booleanValue; - case 2 /* TypeOrder.NumberValue */: - return normalizeNumber(value.integerValue || value.doubleValue); - case 3 /* TypeOrder.TimestampValue */: - return this.convertTimestamp(value.timestampValue); - case 4 /* TypeOrder.ServerTimestampValue */: - return this.convertServerTimestamp(value, serverTimestampBehavior); - case 5 /* TypeOrder.StringValue */: - return value.stringValue; - case 6 /* TypeOrder.BlobValue */: - return this.convertBytes(normalizeByteString(value.bytesValue)); - case 7 /* TypeOrder.RefValue */: - return this.convertReference(value.referenceValue); - case 8 /* TypeOrder.GeoPointValue */: - return this.convertGeoPoint(value.geoPointValue); - case 9 /* TypeOrder.ArrayValue */: - return this.convertArray(value.arrayValue, serverTimestampBehavior); - case 11 /* TypeOrder.ObjectValue */: - return this.convertObject(value.mapValue, serverTimestampBehavior); - case 10 /* TypeOrder.VectorValue */: - return this.convertVectorValue(value.mapValue); - default: - throw fail(); - } - } - convertObject(mapValue, serverTimestampBehavior) { - return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); - } - /** - * @internal - */ - convertObjectMap(fields, serverTimestampBehavior = 'none') { - const result = {}; - forEach(fields, (key, value) => { - result[key] = this.convertValue(value, serverTimestampBehavior); - }); - return result; - } - /** - * @internal - */ - convertVectorValue(mapValue) { - var _a, _b, _c; - const values = (_c = (_b = (_a = mapValue.fields) === null || _a === void 0 ? void 0 : _a[VECTOR_MAP_VECTORS_KEY].arrayValue) === null || _b === void 0 ? void 0 : _b.values) === null || _c === void 0 ? void 0 : _c.map(value => { - return normalizeNumber(value.doubleValue); - }); - return new VectorValue(values); - } - convertGeoPoint(value) { - return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); - } - convertArray(arrayValue, serverTimestampBehavior) { - return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); - } - convertServerTimestamp(value, serverTimestampBehavior) { - switch (serverTimestampBehavior) { - case 'previous': - const previousValue = getPreviousValue(value); - if (previousValue == null) { - return null; - } - return this.convertValue(previousValue, serverTimestampBehavior); - case 'estimate': - return this.convertTimestamp(getLocalWriteTime(value)); - default: - return null; - } - } - convertTimestamp(value) { - const normalizedValue = normalizeTimestamp(value); - return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); - } - convertDocumentKey(name, expectedDatabaseId) { - const resourcePath = ResourcePath.fromString(name); - hardAssert(isValidResourceName(resourcePath)); - const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); - const key = new DocumentKey(resourcePath.popFirst(5)); - if (!databaseId.isEqual(expectedDatabaseId)) { - // TODO(b/64130202): Somehow support foreign references. - logError(`Document ${key} contains a document ` + - `reference within a different database (` + - `${databaseId.projectId}/${databaseId.database}) which is not ` + - `supported. It will be treated as a reference in the current ` + - `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + - `instead.`); - } - return key; - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Converts custom model object of type T into `DocumentData` by applying the - * converter if it exists. - * - * This function is used when converting user objects to `DocumentData` - * because we want to provide the user with a more specific error message if - * their `set()` or fails due to invalid data originating from a `toFirestore()` - * call. - */ - function applyFirestoreDataConverter(converter, value, options) { - let convertedValue; - if (converter) { - if (options && (options.merge || options.mergeFields)) { - // Cast to `any` in order to satisfy the union type constraint on - // toFirestore(). - // eslint-disable-next-line @typescript-eslint/no-explicit-any - convertedValue = converter.toFirestore(value, options); - } - else { - convertedValue = converter.toFirestore(value); - } - } - else { - convertedValue = value; - } - return convertedValue; - } - class LiteUserDataWriter extends AbstractUserDataWriter { - constructor(firestore) { - super(); - this.firestore = firestore; - } - convertBytes(bytes) { - return new Bytes(bytes); - } - convertReference(name) { - const key = this.convertDocumentKey(name, this.firestore._databaseId); - return new DocumentReference(this.firestore, /* converter= */ null, key); - } - } - /** - * Reads the document referred to by the specified document reference. - * - * All documents are directly fetched from the server, even if the document was - * previously read or modified. Recent modifications are only reflected in the - * retrieved `DocumentSnapshot` if they have already been applied by the - * backend. If the client is offline, the read fails. If you like to use - * caching or see local modifications, please use the full Firestore SDK. - * - * @param reference - The reference of the document to fetch. - * @returns A Promise resolved with a `DocumentSnapshot` containing the current - * document contents. - */ - function getDoc(reference) { - reference = cast(reference, DocumentReference); - const datastore = getDatastore(reference.firestore); - const userDataWriter = new LiteUserDataWriter(reference.firestore); - return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => { - hardAssert(result.length === 1); - const document = result[0]; - return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter); - }); - } - /** - * Executes the query and returns the results as a {@link QuerySnapshot}. - * - * All queries are executed directly by the server, even if the query was - * previously executed. Recent modifications are only reflected in the retrieved - * results if they have already been applied by the backend. If the client is - * offline, the operation fails. To see previously cached result and local - * modifications, use the full Firestore SDK. - * - * @param query - The `Query` to execute. - * @returns A Promise that will be resolved with the results of the query. - */ - function getDocs(query) { - query = cast(query, Query); - validateHasExplicitOrderByForLimitToLast(query._query); - const datastore = getDatastore(query.firestore); - const userDataWriter = new LiteUserDataWriter(query.firestore); - return invokeRunQueryRpc(datastore, query._query).then(result => { - const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter)); - if (query._query.limitType === "L" /* LimitType.Last */) { - // Limit to last queries reverse the orderBy constraint that was - // specified by the user. As such, we need to reverse the order of the - // results to return the documents in the expected order. - docs.reverse(); - } - return new QuerySnapshot(query, docs); - }); - } - function setDoc(reference, data, options) { - reference = cast(reference, DocumentReference); - const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); - const dataReader = newUserDataReader(reference.firestore); - const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - parsed.toMutation(reference._key, Precondition.none()) - ]); - } - function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { - reference = cast(reference, DocumentReference); - const dataReader = newUserDataReader(reference.firestore); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); - let parsed; - if (typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath) { - parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); - } - else { - parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); - } - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - parsed.toMutation(reference._key, Precondition.exists(true)) - ]); - } - /** - * Deletes the document referred to by the specified `DocumentReference`. - * - * The deletion will only be reflected in document reads that occur after the - * returned promise resolves. If the client is offline, the - * delete fails. If you would like to see local modifications or buffer writes - * until the client is online, use the full Firestore SDK. - * - * @param reference - A reference to the document to delete. - * @returns A `Promise` resolved once the document has been successfully - * deleted from the backend. - */ - function deleteDoc(reference) { - reference = cast(reference, DocumentReference); - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - new DeleteMutation(reference._key, Precondition.none()) - ]); - } - /** - * Add a new document to specified `CollectionReference` with the given data, - * assigning it a document ID automatically. - * - * The result of this write will only be reflected in document reads that occur - * after the returned promise resolves. If the client is offline, the - * write fails. If you would like to see local modifications or buffer writes - * until the client is online, use the full Firestore SDK. - * - * @param reference - A reference to the collection to add this document to. - * @param data - An Object containing the data for the new document. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns A `Promise` resolved with a `DocumentReference` pointing to the - * newly created document after it has been written to the backend. - */ - function addDoc(reference, data) { - reference = cast(reference, CollectionReference); - const docRef = doc(reference); - const convertedValue = applyFirestoreDataConverter(reference.converter, data); - const dataReader = newUserDataReader(reference.firestore); - const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {}); - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - parsed.toMutation(docRef._key, Precondition.exists(false)) - ]).then(() => docRef); - } - - /** - * @license - * Copyright 2022 Google LLC - * - * 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. - */ - /** - * Calculates the number of documents in the result set of the given query - * without actually downloading the documents. - * - * Using this function to count the documents is efficient because only the - * final count, not the documents' data, is downloaded. This function can - * count the documents in cases where the result set is prohibitively large to - * download entirely (thousands of documents). - * - * @param query The query whose result set size is calculated. - * @returns A Promise that will be resolved with the count; the count can be - * retrieved from `snapshot.data().count`, where `snapshot` is the - * `AggregateQuerySnapshot` to which the returned Promise resolves. - */ - function getCount(query) { - const countQuerySpec = { - count: count() - }; - return getAggregate(query, countQuerySpec); - } - /** - * Calculates the specified aggregations over the documents in the result - * set of the given query without actually downloading the documents. - * - * Using this function to perform aggregations is efficient because only the - * final aggregation values, not the documents' data, are downloaded. This - * function can perform aggregations of the documents in cases where the result - * set is prohibitively large to download entirely (thousands of documents). - * - * @param query The query whose result set is aggregated over. - * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates - * to perform over the result set. The AggregateSpec specifies aliases for each - * aggregate, which can be used to retrieve the aggregate result. - * @example - * ```typescript - * const aggregateSnapshot = await getAggregate(query, { - * countOfDocs: count(), - * totalHours: sum('hours'), - * averageScore: average('score') - * }); - * - * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; - * const totalHours: number = aggregateSnapshot.data().totalHours; - * const averageScore: number | null = aggregateSnapshot.data().averageScore; - * ``` - */ - function getAggregate(query, aggregateSpec) { - const firestore = cast(query.firestore, Firestore); - const datastore = getDatastore(firestore); - const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { - return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); - }); - // Run the aggregation and convert the results - return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); - } - function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { - const userDataWriter = new LiteUserDataWriter(firestore); - const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); - return querySnapshot; - } - /** - * Create an AggregateField object that can be used to compute the sum of - * a specified field over a range of documents in the result set of a query. - * @param field Specifies the field to sum across the result set. - */ - function sum(field) { - return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); - } - /** - * Create an AggregateField object that can be used to compute the average of - * a specified field over a range of documents in the result set of a query. - * @param field Specifies the field to average across the result set. - */ - function average(field) { - return new AggregateField('avg', fieldPathFromArgument$1('average', field)); - } - /** - * Create an AggregateField object that can be used to compute the count of - * documents in the result set of a query. - */ - function count() { - return new AggregateField('count'); - } - /** - * Compares two 'AggregateField` instances for equality. - * - * @param left Compare this AggregateField to the `right`. - * @param right Compare this AggregateField to the `left`. - */ - function aggregateFieldEqual(left, right) { - var _a, _b; - return (left instanceof AggregateField && - right instanceof AggregateField && - left.aggregateType === right.aggregateType && - ((_a = left._internalFieldPath) === null || _a === void 0 ? void 0 : _a.canonicalString()) === - ((_b = right._internalFieldPath) === null || _b === void 0 ? void 0 : _b.canonicalString())); - } - /** - * Compares two `AggregateQuerySnapshot` instances for equality. - * - * Two `AggregateQuerySnapshot` instances are considered "equal" if they have - * underlying queries that compare equal, and the same data. - * - * @param left - The first `AggregateQuerySnapshot` to compare. - * @param right - The second `AggregateQuerySnapshot` to compare. - * - * @returns `true` if the objects are "equal", as defined above, or `false` - * otherwise. - */ - function aggregateQuerySnapshotEqual(left, right) { - return (queryEqual(left.query, right.query) && util.deepEqual(left.data(), right.data())); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or - * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. - */ - function deleteField() { - return new DeleteFieldValueImpl('deleteField'); - } - /** - * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to - * include a server-generated timestamp in the written data. - */ - function serverTimestamp() { - return new ServerTimestampFieldValueImpl('serverTimestamp'); - } - /** - * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link - * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array - * value that already exists on the server. Each specified element that doesn't - * already exist in the array will be added to the end. If the field being - * modified is not already an array it will be overwritten with an array - * containing exactly the specified elements. - * - * @param elements - The elements to union into the array. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()`. - */ - function arrayUnion(...elements) { - // NOTE: We don't actually parse the data until it's used in set() or - // update() since we'd need the Firestore instance to do this. - return new ArrayUnionFieldValueImpl('arrayUnion', elements); - } - /** - * Returns a special value that can be used with {@link (setDoc:1)} or {@link - * updateDoc:1} that tells the server to remove the given elements from any - * array value that already exists on the server. All instances of each element - * specified will be removed from the array. If the field being modified is not - * already an array it will be overwritten with an empty array. - * - * @param elements - The elements to remove from the array. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()` - */ - function arrayRemove(...elements) { - // NOTE: We don't actually parse the data until it's used in set() or - // update() since we'd need the Firestore instance to do this. - return new ArrayRemoveFieldValueImpl('arrayRemove', elements); - } - /** - * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link - * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by - * the given value. - * - * If either the operand or the current field value uses floating point - * precision, all arithmetic follows IEEE 754 semantics. If both values are - * integers, values outside of JavaScript's safe number range - * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to - * precision loss. Furthermore, once processed by the Firestore backend, all - * integer operations are capped between -2^63 and 2^63-1. - * - * If the current field value is not of type `number`, or if the field does not - * yet exist, the transformation sets the field to the given value. - * - * @param n - The value to increment by. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()` - */ - function increment(n) { - return new NumericIncrementFieldValueImpl('increment', n); - } - /** - * Creates a new `VectorValue` constructed with a copy of the given array of numbers. - * - * @param values - Create a `VectorValue` instance with a copy of this array of numbers. - * - * @returns A new `VectorValue` constructed with a copy of the given array of numbers. - */ - function vector(values) { - return new VectorValue(values); - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - /** - * A write batch, used to perform multiple writes as a single atomic unit. - * - * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It - * provides methods for adding writes to the write batch. None of the writes - * will be committed (or visible locally) until {@link WriteBatch.commit} is - * called. - */ - class WriteBatch { - /** @hideconstructor */ - constructor(_firestore, _commitHandler) { - this._firestore = _firestore; - this._commitHandler = _commitHandler; - this._mutations = []; - this._committed = false; - this._dataReader = newUserDataReader(_firestore); - } - set(documentRef, data, options) { - this._verifyNotCommitted(); - const ref = validateReference(documentRef, this._firestore); - const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); - const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); - this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); - return this; - } - update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { - this._verifyNotCommitted(); - const ref = validateReference(documentRef, this._firestore); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); - let parsed; - if (typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath) { - parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); - } - else { - parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); - } - this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); - return this; - } - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - delete(documentRef) { - this._verifyNotCommitted(); - const ref = validateReference(documentRef, this._firestore); - this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); - return this; - } - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * The result of these writes will only be reflected in document reads that - * occur after the returned promise resolves. If the client is offline, the - * write fails. If you would like to see local modifications or buffer writes - * until the client is online, use the full Firestore SDK. - * - * @returns A `Promise` resolved once all of the writes in the batch have been - * successfully written to the backend as an atomic unit (note that it won't - * resolve while you're offline). - */ - commit() { - this._verifyNotCommitted(); - this._committed = true; - if (this._mutations.length > 0) { - return this._commitHandler(this._mutations); - } - return Promise.resolve(); - } - _verifyNotCommitted() { - if (this._committed) { - throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + - 'has been called.'); - } - } - } - function validateReference(documentRef, firestore) { - documentRef = util.getModularInstance(documentRef); - if (documentRef.firestore !== firestore) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); - } - else { - return documentRef; - } - } - /** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. The maximum number of writes allowed in a single WriteBatch - * is 500. - * - * The result of these writes will only be reflected in document reads that - * occur after the returned promise resolves. If the client is offline, the - * write fails. If you would like to see local modifications or buffer writes - * until the client is online, use the full Firestore SDK. - * - * @returns A `WriteBatch` that can be used to atomically execute multiple - * writes. - */ - function writeBatch(firestore) { - firestore = cast(firestore, Firestore); - const datastore = getDatastore(firestore); - return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes)); - } - - /** - * @license - * Copyright 2022 Google LLC - * - * 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. - */ - const DEFAULT_TRANSACTION_OPTIONS = { - maxAttempts: 5 - }; - function validateTransactionOptions(options) { - if (options.maxAttempts < 1) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Internal transaction object responsible for accumulating the mutations to - * perform and the base versions for any documents read. - */ - class Transaction$1 { - constructor(datastore) { - this.datastore = datastore; - // The version of each document that was read during this transaction. - this.readVersions = new Map(); - this.mutations = []; - this.committed = false; - /** - * A deferred usage error that occurred previously in this transaction that - * will cause the transaction to fail once it actually commits. - */ - this.lastTransactionError = null; - /** - * Set of documents that have been written in the transaction. - * - * When there's more than one write to the same key in a transaction, any - * writes after the first are handled differently. - */ - this.writtenDocs = new Set(); - } - async lookup(keys) { - this.ensureCommitNotCalled(); - if (this.mutations.length > 0) { - this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); - throw this.lastTransactionError; - } - const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); - docs.forEach(doc => this.recordVersion(doc)); - return docs; - } - set(key, data) { - this.write(data.toMutation(key, this.precondition(key))); - this.writtenDocs.add(key.toString()); - } - update(key, data) { - try { - this.write(data.toMutation(key, this.preconditionForUpdate(key))); - } - catch (e) { - this.lastTransactionError = e; - } - this.writtenDocs.add(key.toString()); - } - delete(key) { - this.write(new DeleteMutation(key, this.precondition(key))); - this.writtenDocs.add(key.toString()); - } - async commit() { - this.ensureCommitNotCalled(); - if (this.lastTransactionError) { - throw this.lastTransactionError; - } - const unwritten = this.readVersions; - // For each mutation, note that the doc was written. - this.mutations.forEach(mutation => { - unwritten.delete(mutation.key.toString()); - }); - // For each document that was read but not written to, we want to perform - // a `verify` operation. - unwritten.forEach((_, path) => { - const key = DocumentKey.fromPath(path); - this.mutations.push(new VerifyMutation(key, this.precondition(key))); - }); - await invokeCommitRpc(this.datastore, this.mutations); - this.committed = true; - } - recordVersion(doc) { - let docVersion; - if (doc.isFoundDocument()) { - docVersion = doc.version; - } - else if (doc.isNoDocument()) { - // Represent a deleted doc using SnapshotVersion.min(). - docVersion = SnapshotVersion.min(); - } - else { - throw fail(); - } - const existingVersion = this.readVersions.get(doc.key.toString()); - if (existingVersion) { - if (!docVersion.isEqual(existingVersion)) { - // This transaction will fail no matter what. - throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); - } - } - else { - this.readVersions.set(doc.key.toString(), docVersion); - } - } - /** - * Returns the version of this document when it was read in this transaction, - * as a precondition, or no precondition if it was not read. - */ - precondition(key) { - const version = this.readVersions.get(key.toString()); - if (!this.writtenDocs.has(key.toString()) && version) { - if (version.isEqual(SnapshotVersion.min())) { - return Precondition.exists(false); - } - else { - return Precondition.updateTime(version); - } - } - else { - return Precondition.none(); - } - } - /** - * Returns the precondition for a document if the operation is an update. - */ - preconditionForUpdate(key) { - const version = this.readVersions.get(key.toString()); - // The first time a document is written, we want to take into account the - // read time and existence - if (!this.writtenDocs.has(key.toString()) && version) { - if (version.isEqual(SnapshotVersion.min())) { - // The document doesn't exist, so fail the transaction. - // This has to be validated locally because you can't send a - // precondition that a document does not exist without changing the - // semantics of the backend write to be an insert. This is the reverse - // of what we want, since we want to assert that the document doesn't - // exist but then send the update and have it fail. Since we can't - // express that to the backend, we have to validate locally. - // Note: this can change once we can send separate verify writes in the - // transaction. - throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); - } - // Document exists, base precondition on document update time. - return Precondition.updateTime(version); - } - else { - // Document was not read, so we just use the preconditions for a blind - // update. - return Precondition.exists(true); - } - } - write(mutation) { - this.ensureCommitNotCalled(); - this.mutations.push(mutation); - } - ensureCommitNotCalled() { - } - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - /** - * TransactionRunner encapsulates the logic needed to run and retry transactions - * with backoff. - */ - class TransactionRunner { - constructor(asyncQueue, datastore, options, updateFunction, deferred) { - this.asyncQueue = asyncQueue; - this.datastore = datastore; - this.options = options; - this.updateFunction = updateFunction; - this.deferred = deferred; - this.attemptsRemaining = options.maxAttempts; - this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); - } - /** Runs the transaction and sets the result on deferred. */ - run() { - this.attemptsRemaining -= 1; - this.runWithBackOff(); - } - runWithBackOff() { - this.backoff.backoffAndRun(async () => { - const transaction = new Transaction$1(this.datastore); - const userPromise = this.tryRunUpdateFunction(transaction); - if (userPromise) { - userPromise - .then(result => { - this.asyncQueue.enqueueAndForget(() => { - return transaction - .commit() - .then(() => { - this.deferred.resolve(result); - }) - .catch(commitError => { - this.handleTransactionError(commitError); - }); - }); - }) - .catch(userPromiseError => { - this.handleTransactionError(userPromiseError); - }); - } - }); - } - tryRunUpdateFunction(transaction) { - try { - const userPromise = this.updateFunction(transaction); - if (isNullOrUndefined(userPromise) || - !userPromise.catch || - !userPromise.then) { - this.deferred.reject(Error('Transaction callback must return a Promise')); - return null; - } - return userPromise; - } - catch (error) { - // Do not retry errors thrown by user provided updateFunction. - this.deferred.reject(error); - return null; - } - } - handleTransactionError(error) { - if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { - this.attemptsRemaining -= 1; - this.asyncQueue.enqueueAndForget(() => { - this.runWithBackOff(); - return Promise.resolve(); - }); - } - else { - this.deferred.reject(error); - } - } - isRetryableTransactionError(error) { - if (error.name === 'FirebaseError') { - // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and - // non-matching document versions with ABORTED. These errors should be retried. - const code = error.code; - return (code === 'aborted' || - code === 'failed-precondition' || - code === 'already-exists' || - !isPermanentError(code)); - } - return false; - } - } - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * Represents an operation scheduled to be run in the future on an AsyncQueue. - * - * It is created via DelayedOperation.createAndSchedule(). - * - * Supports cancellation (via cancel()) and early execution (via skipDelay()). - * - * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type - * in newer versions of TypeScript defines `finally`, which is not available in - * IE. - */ - class DelayedOperation { - constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { - this.asyncQueue = asyncQueue; - this.timerId = timerId; - this.targetTimeMs = targetTimeMs; - this.op = op; - this.removalCallback = removalCallback; - this.deferred = new Deferred(); - this.then = this.deferred.promise.then.bind(this.deferred.promise); - // It's normal for the deferred promise to be canceled (due to cancellation) - // and so we attach a dummy catch callback to avoid - // 'UnhandledPromiseRejectionWarning' log spam. - this.deferred.promise.catch(err => { }); - } - get promise() { - return this.deferred.promise; - } - /** - * Creates and returns a DelayedOperation that has been scheduled to be - * executed on the provided asyncQueue after the provided delayMs. - * - * @param asyncQueue - The queue to schedule the operation on. - * @param id - A Timer ID identifying the type of operation this is. - * @param delayMs - The delay (ms) before the operation should be scheduled. - * @param op - The operation to run. - * @param removalCallback - A callback to be called synchronously once the - * operation is executed or canceled, notifying the AsyncQueue to remove it - * from its delayedOperations list. - * PORTING NOTE: This exists to prevent making removeDelayedOperation() and - * the DelayedOperation class public. - */ - static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { - const targetTime = Date.now() + delayMs; - const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); - delayedOp.start(delayMs); - return delayedOp; - } - /** - * Starts the timer. This is called immediately after construction by - * createAndSchedule(). - */ - start(delayMs) { - this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); - } - /** - * Queues the operation to run immediately (if it hasn't already been run or - * canceled). - */ - skipDelay() { - return this.handleDelayElapsed(); - } - /** - * Cancels the operation if it hasn't already been executed or canceled. The - * promise will be rejected. - * - * As long as the operation has not yet been run, calling cancel() provides a - * guarantee that the operation will not be run. - */ - cancel(reason) { - if (this.timerHandle !== null) { - this.clearTimeout(); - this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); - } - } - handleDelayElapsed() { - this.asyncQueue.enqueueAndForget(() => { - if (this.timerHandle !== null) { - this.clearTimeout(); - return this.op().then(result => { - return this.deferred.resolve(result); - }); - } - else { - return Promise.resolve(); - } - }); - } - clearTimeout() { - if (this.timerHandle !== null) { - this.removalCallback(this); - clearTimeout(this.timerHandle); - this.timerHandle = null; - } - } - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - const LOG_TAG = 'AsyncQueue'; - class AsyncQueueImpl { - constructor(tail = Promise.resolve()) { - // A list of retryable operations. Retryable operations are run in order and - // retried with backoff. - this.retryableOps = []; - // Is this AsyncQueue being shut down? Once it is set to true, it will not - // be changed again. - this._isShuttingDown = false; - // Operations scheduled to be queued in the future. Operations are - // automatically removed after they are run or canceled. - this.delayedOperations = []; - // visible for testing - this.failure = null; - // Flag set while there's an outstanding AsyncQueue operation, used for - // assertion sanity-checks. - this.operationInProgress = false; - // Enabled during shutdown on Safari to prevent future access to IndexedDB. - this.skipNonRestrictedTasks = false; - // List of TimerIds to fast-forward delays for. - this.timerIdsToSkip = []; - // Backoff timer used to schedule retries for retryable operations - this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); - // Visibility handler that triggers an immediate retry of all retryable - // operations. Meant to speed up recovery when we regain file system access - // after page comes into foreground. - this.visibilityHandler = () => { - this.backoff.skipBackoff(); - }; - this.tail = tail; - } - get isShuttingDown() { - return this._isShuttingDown; - } - /** - * Adds a new operation to the queue without waiting for it to complete (i.e. - * we ignore the Promise result). - */ - enqueueAndForget(op) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - this.enqueue(op); - } - enqueueAndForgetEvenWhileRestricted(op) { - this.verifyNotFailed(); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - this.enqueueInternal(op); - } - enterRestrictedMode(purgeExistingTasks) { - if (!this._isShuttingDown) { - this._isShuttingDown = true; - this.skipNonRestrictedTasks = purgeExistingTasks || false; - } - } - enqueue(op) { - this.verifyNotFailed(); - if (this._isShuttingDown) { - // Return a Promise which never resolves. - return new Promise(() => { }); - } - // Create a deferred Promise that we can return to the callee. This - // allows us to return a "hanging Promise" only to the callee and still - // advance the queue even when the operation is not run. - const task = new Deferred(); - return this.enqueueInternal(() => { - if (this._isShuttingDown && this.skipNonRestrictedTasks) { - // We do not resolve 'task' - return Promise.resolve(); - } - op().then(task.resolve, task.reject); - return task.promise; - }).then(() => task.promise); - } - enqueueRetryable(op) { - this.enqueueAndForget(() => { - this.retryableOps.push(op); - return this.retryNextOp(); - }); - } - /** - * Runs the next operation from the retryable queue. If the operation fails, - * reschedules with backoff. - */ - async retryNextOp() { - if (this.retryableOps.length === 0) { - return; - } - try { - await this.retryableOps[0](); - this.retryableOps.shift(); - this.backoff.reset(); - } - catch (e) { - if (isIndexedDbTransactionError(e)) { - logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); - } - else { - throw e; // Failure will be handled by AsyncQueue - } - } - if (this.retryableOps.length > 0) { - // If there are additional operations, we re-schedule `retryNextOp()`. - // This is necessary to run retryable operations that failed during - // their initial attempt since we don't know whether they are already - // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` - // needs to be re-run, we will run `op1`, `op1`, `op2` using the - // already enqueued calls to `retryNextOp()`. `op3()` will then run in the - // call scheduled here. - // Since `backoffAndRun()` cancels an existing backoff and schedules a - // new backoff on every call, there is only ever a single additional - // operation in the queue. - this.backoff.backoffAndRun(() => this.retryNextOp()); - } - } - enqueueInternal(op) { - const newTail = this.tail.then(() => { - this.operationInProgress = true; - return op() - .catch((error) => { - this.failure = error; - this.operationInProgress = false; - const message = getMessageOrStack(error); - logError('INTERNAL UNHANDLED ERROR: ', message); - // Re-throw the error so that this.tail becomes a rejected Promise and - // all further attempts to chain (via .then) will just short-circuit - // and return the rejected Promise. - throw error; - }) - .then(result => { - this.operationInProgress = false; - return result; - }); - }); - this.tail = newTail; - return newTail; - } - enqueueAfterDelay(timerId, delayMs, op) { - this.verifyNotFailed(); - // Fast-forward delays for timerIds that have been overridden. - if (this.timerIdsToSkip.indexOf(timerId) > -1) { - delayMs = 0; - } - const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); - this.delayedOperations.push(delayedOp); - return delayedOp; - } - verifyNotFailed() { - if (this.failure) { - fail(); - } - } - verifyOperationInProgress() { - } - /** - * Waits until all currently queued tasks are finished executing. Delayed - * operations are not run. - */ - async drain() { - // Operations in the queue prior to draining may have enqueued additional - // operations. Keep draining the queue until the tail is no longer advanced, - // which indicates that no more new operations were enqueued and that all - // operations were executed. - let currentTail; - do { - currentTail = this.tail; - await currentTail; - } while (currentTail !== this.tail); - } - /** - * For Tests: Determine if a delayed operation with a particular TimerId - * exists. - */ - containsDelayedOperation(timerId) { - for (const op of this.delayedOperations) { - if (op.timerId === timerId) { - return true; - } - } - return false; - } - /** - * For Tests: Runs some or all delayed operations early. - * - * @param lastTimerId - Delayed operations up to and including this TimerId - * will be drained. Pass TimerId.All to run all delayed operations. - * @returns a Promise that resolves once all operations have been run. - */ - runAllDelayedOperationsUntil(lastTimerId) { - // Note that draining may generate more delayed ops, so we do that first. - return this.drain().then(() => { - // Run ops in the same order they'd run if they ran naturally. - /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ - this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); - for (const op of this.delayedOperations) { - op.skipDelay(); - if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { - break; - } - } - return this.drain(); - }); - } - /** - * For Tests: Skip all subsequent delays for a timer id. - */ - skipDelaysForTimerId(timerId) { - this.timerIdsToSkip.push(timerId); - } - /** Called once a DelayedOperation is run or canceled. */ - removeDelayedOperation(op) { - // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. - const index = this.delayedOperations.indexOf(op); - /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ - this.delayedOperations.splice(index, 1); - } - } - function newAsyncQueue() { - return new AsyncQueueImpl(); - } - /** - * Chrome includes Error.message in Error.stack. Other browsers do not. - * This returns expected output of message + stack when available. - * @param error - Error or FirestoreError - */ - function getMessageOrStack(error) { - let message = error.message || ''; - if (error.stack) { - if (error.stack.includes(error.message)) { - message = error.stack; - } - else { - message = error.message + '\n' + error.stack; - } - } - return message; - } - - /** - * @license - * Copyright 2020 Google LLC - * - * 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. - */ - // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the - // legacy SDK. - /** - * A reference to a transaction. - * - * The `Transaction` object passed to a transaction's `updateFunction` provides - * the methods to read and write data within the transaction context. See - * {@link runTransaction}. - */ - class Transaction { - /** @hideconstructor */ - constructor(_firestore, _transaction) { - this._firestore = _firestore; - this._transaction = _transaction; - this._dataReader = newUserDataReader(_firestore); - } - /** - * Reads the document referenced by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be read. - * @returns A `DocumentSnapshot` with the read data. - */ - get(documentRef) { - const ref = validateReference(documentRef, this._firestore); - const userDataWriter = new LiteUserDataWriter(this._firestore); - return this._transaction.lookup([ref._key]).then(docs => { - if (!docs || docs.length !== 1) { - return fail(); - } - const doc = docs[0]; - if (doc.isFoundDocument()) { - return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter); - } - else if (doc.isNoDocument()) { - return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter); - } - else { - throw fail(); - } - }); - } - set(documentRef, value, options) { - const ref = validateReference(documentRef, this._firestore); - const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); - const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); - this._transaction.set(ref._key, parsed); - return this; - } - update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { - const ref = validateReference(documentRef, this._firestore); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); - let parsed; - if (typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath) { - parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); - } - else { - parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); - } - this._transaction.update(ref._key, parsed); - return this; - } - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - delete(documentRef) { - const ref = validateReference(documentRef, this._firestore); - this._transaction.delete(ref._key); - return this; - } - } - /** - * Executes the given `updateFunction` and then attempts to commit the changes - * applied within the transaction. If any document read within the transaction - * has changed, Cloud Firestore retries the `updateFunction`. If it fails to - * commit after 5 attempts, the transaction fails. - * - * The maximum number of writes allowed in a single transaction is 500. - * - * @param firestore - A reference to the Firestore database to run this - * transaction against. - * @param updateFunction - The function to execute within the transaction - * context. - * @param options - An options object to configure maximum number of attempts to - * commit. - * @returns If the transaction completed successfully or was explicitly aborted - * (the `updateFunction` returned a failed promise), the promise returned by the - * `updateFunction `is returned here. Otherwise, if the transaction failed, a - * rejected promise with the corresponding failure error is returned. - */ - function runTransaction(firestore, updateFunction, options) { - firestore = cast(firestore, Firestore); - const datastore = getDatastore(firestore); - const optionsWithDefaults = Object.assign(Object.assign({}, DEFAULT_TRANSACTION_OPTIONS), options); - validateTransactionOptions(optionsWithDefaults); - const deferred = new Deferred(); - new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run(); - return deferred.promise; - } - - /** - * Firestore Lite - * - * @remarks Firestore Lite is a small online-only SDK that allows read - * and write access to your Firestore database. All operations connect - * directly to the backend, and `onSnapshot()` APIs are not supported. - * @packageDocumentation - */ - registerFirestore(); - - index_node_cjs.AggregateField = AggregateField; - index_node_cjs.AggregateQuerySnapshot = AggregateQuerySnapshot; - index_node_cjs.Bytes = Bytes; - index_node_cjs.CollectionReference = CollectionReference; - index_node_cjs.DocumentReference = DocumentReference; - index_node_cjs.DocumentSnapshot = DocumentSnapshot; - index_node_cjs.FieldPath = FieldPath; - index_node_cjs.FieldValue = FieldValue; - index_node_cjs.Firestore = Firestore; - index_node_cjs.FirestoreError = FirestoreError; - index_node_cjs.GeoPoint = GeoPoint; - index_node_cjs.Query = Query; - index_node_cjs.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint; - index_node_cjs.QueryConstraint = QueryConstraint; - index_node_cjs.QueryDocumentSnapshot = QueryDocumentSnapshot; - index_node_cjs.QueryEndAtConstraint = QueryEndAtConstraint; - index_node_cjs.QueryFieldFilterConstraint = QueryFieldFilterConstraint; - index_node_cjs.QueryLimitConstraint = QueryLimitConstraint; - index_node_cjs.QueryOrderByConstraint = QueryOrderByConstraint; - index_node_cjs.QuerySnapshot = QuerySnapshot; - index_node_cjs.QueryStartAtConstraint = QueryStartAtConstraint; - index_node_cjs.Timestamp = Timestamp; - index_node_cjs.Transaction = Transaction; - index_node_cjs.VectorValue = VectorValue; - index_node_cjs.WriteBatch = WriteBatch; - index_node_cjs.addDoc = addDoc; - index_node_cjs.aggregateFieldEqual = aggregateFieldEqual; - index_node_cjs.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual; - index_node_cjs.and = and; - index_node_cjs.arrayRemove = arrayRemove; - index_node_cjs.arrayUnion = arrayUnion; - index_node_cjs.average = average; - index_node_cjs.collection = collection; - index_node_cjs.collectionGroup = collectionGroup; - index_node_cjs.connectFirestoreEmulator = connectFirestoreEmulator; - index_node_cjs.count = count; - index_node_cjs.deleteDoc = deleteDoc; - index_node_cjs.deleteField = deleteField; - index_node_cjs.doc = doc; - index_node_cjs.documentId = documentId; - index_node_cjs.endAt = endAt; - index_node_cjs.endBefore = endBefore; - index_node_cjs.getAggregate = getAggregate; - index_node_cjs.getCount = getCount; - index_node_cjs.getDoc = getDoc; - index_node_cjs.getDocs = getDocs; - index_node_cjs.getFirestore = getFirestore; - index_node_cjs.increment = increment; - index_node_cjs.initializeFirestore = initializeFirestore; - index_node_cjs.limit = limit; - index_node_cjs.limitToLast = limitToLast; - index_node_cjs.or = or; - index_node_cjs.orderBy = orderBy; - index_node_cjs.query = query; - index_node_cjs.queryEqual = queryEqual; - index_node_cjs.refEqual = refEqual; - index_node_cjs.runTransaction = runTransaction; - index_node_cjs.serverTimestamp = serverTimestamp; - index_node_cjs.setDoc = setDoc; - index_node_cjs.setLogLevel = setLogLevel; - index_node_cjs.snapshotEqual = snapshotEqual; - index_node_cjs.startAfter = startAfter; - index_node_cjs.startAt = startAt; - index_node_cjs.sum = sum; - index_node_cjs.terminate = terminate; - index_node_cjs.updateDoc = updateDoc; - index_node_cjs.vector = vector; - index_node_cjs.where = where; - index_node_cjs.writeBatch = writeBatch; - - (function (exports) { - - Object.defineProperty(exports, '__esModule', { value: true }); - - var lite = index_node_cjs; - - - - Object.keys(lite).forEach(function (k) { - if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return lite[k]; } - }); - }); - - } (index_cjs)); - - let exp = index_cjs?.default || index_cjs || { __emptyModule: true };try { Object.defineProperty(exp, "__" + "esModule", { value: true }); exp.default = exp; } catch (ex) {} - - return exp; + /** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = Object.assign(Object.assign({}, z), r); + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(T, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).At(), s.promise; + } + + /** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + d = t; + }(`${index_esm2017.SDK_VERSION}_lite`), index_esm2017._registerComponent(new index_esm2017.Component("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(T, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + } + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ (n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + index_esm2017.registerVersion("firestore-lite", "4.7.4", ""), index_esm2017.registerVersion("firestore-lite", "4.7.4", "esm2017"); + }(); + + const __esModule = true; + + exports.AggregateField = AggregateField; + exports.AggregateQuerySnapshot = AggregateQuerySnapshot; + exports.Bytes = Bytes; + exports.CollectionReference = CollectionReference; + exports.DocumentReference = DocumentReference; + exports.DocumentSnapshot = DocumentSnapshot; + exports.FieldPath = FieldPath; + exports.FieldValue = FieldValue; + exports.Firestore = Firestore; + exports.FirestoreError = FirestoreError; + exports.GeoPoint = GeoPoint; + exports.Query = Query; + exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint; + exports.QueryConstraint = QueryConstraint; + exports.QueryDocumentSnapshot = QueryDocumentSnapshot; + exports.QueryEndAtConstraint = QueryEndAtConstraint; + exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint; + exports.QueryLimitConstraint = QueryLimitConstraint; + exports.QueryOrderByConstraint = QueryOrderByConstraint; + exports.QuerySnapshot = QuerySnapshot; + exports.QueryStartAtConstraint = QueryStartAtConstraint; + exports.Timestamp = Timestamp; + exports.Transaction = Transaction; + exports.VectorValue = VectorValue; + exports.WriteBatch = WriteBatch; + exports.__esModule = __esModule; + exports.addDoc = addDoc; + exports.aggregateFieldEqual = aggregateFieldEqual; + exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual; + exports.and = and; + exports.arrayRemove = arrayRemove; + exports.arrayUnion = arrayUnion; + exports.average = average; + exports.collection = collection; + exports.collectionGroup = collectionGroup; + exports.connectFirestoreEmulator = connectFirestoreEmulator; + exports.count = count; + exports.deleteDoc = deleteDoc; + exports.deleteField = deleteField; + exports.doc = doc; + exports.documentId = documentId; + exports.endAt = endAt; + exports.endBefore = endBefore; + exports.getAggregate = getAggregate; + exports.getCount = getCount; + exports.getDoc = getDoc; + exports.getDocs = getDocs; + exports.getFirestore = getFirestore; + exports.increment = increment; + exports.initializeFirestore = initializeFirestore; + exports.limit = limit; + exports.limitToLast = limitToLast; + exports.or = or; + exports.orderBy = orderBy; + exports.query = query; + exports.queryEqual = queryEqual; + exports.refEqual = refEqual; + exports.runTransaction = runTransaction; + exports.serverTimestamp = serverTimestamp; + exports.setDoc = setDoc; + exports.setLogLevel = setLogLevel; + exports.snapshotEqual = snapshotEqual; + exports.startAfter = startAfter; + exports.startAt = startAt; + exports.sum = sum; + exports.terminate = terminate; + exports.updateDoc = updateDoc; + exports.vector = vector; + exports.where = where; + exports.writeBatch = writeBatch; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.cjs3.js b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.cjs3.js deleted file mode 100644 index fcabe235..00000000 --- a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.cjs3.js +++ /dev/null @@ -1,3502 +0,0 @@ -sap.ui.define(['exports'], (function (exports) { 'use strict'; - - function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var f = n.default; - if (typeof f == "function") { - var a = function a () { - if (this instanceof a) { - return Reflect.construct(f, arguments, this.constructor); - } - return f.apply(this, arguments); - }; - a.prototype = f.prototype; - } else a = {}; - Object.defineProperty(a, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; - } - - var index_cjs$2 = {}; - - var index_cjs$1 = {}; - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } - - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser$1 = true; - var env = {}; - var argv = []; - var version = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop$1() {} - - var on = noop$1; - var addListener = noop$1; - var once = noop$1; - var off = noop$1; - var removeListener = noop$1; - var removeAllListeners = noop$1; - var emit = noop$1; - - function binding(name) { - throw new Error('process.binding is not supported'); - } - - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; - - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds,nanoseconds] - } - - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } - - var browser$1$1 = { - nextTick: nextTick, - title: title, - browser: browser$1, - env: env, - argv: argv, - version: version, - versions: versions, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - const CONSTANTS = { - NODE_CLIENT: false, - NODE_ADMIN: false, - SDK_VERSION: "${JSCORE_VERSION}" - }; - const assert = function (assertion, message) { - if (!assertion) { - throw assertionError(message); - } - }; - const assertionError = function (message) { - return new Error("Firebase Database (" + CONSTANTS.SDK_VERSION + ") INTERNAL ASSERT FAILED: " + message); - }; - const stringToByteArray$1 = function (str) { - const out = []; - let p = 0; - for (let i = 0; i < str.length; i++) { - let c = str.charCodeAt(i); - if (c < 128) { - out[p++] = c; - } else if (c < 2048) { - out[p++] = c >> 6 | 192; - out[p++] = c & 63 | 128; - } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) { - c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023); - out[p++] = c >> 18 | 240; - out[p++] = c >> 12 & 63 | 128; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; - } else { - out[p++] = c >> 12 | 224; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; - } - } - return out; - }; - const byteArrayToString = function (bytes) { - const out = []; - let pos = 0, c = 0; - while (pos < bytes.length) { - const c1 = bytes[pos++]; - if (c1 < 128) { - out[c++] = String.fromCharCode(c1); - } else if (c1 > 191 && c1 < 224) { - const c2 = bytes[pos++]; - out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); - } else if (c1 > 239 && c1 < 365) { - const c2 = bytes[pos++]; - const c3 = bytes[pos++]; - const c4 = bytes[pos++]; - const u = ((c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 65536; - out[c++] = String.fromCharCode(55296 + (u >> 10)); - out[c++] = String.fromCharCode(56320 + (u & 1023)); - } else { - const c2 = bytes[pos++]; - const c3 = bytes[pos++]; - out[c++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63); - } - } - return out.join(""); - }; - const base64 = { - byteToCharMap_: null, - charToByteMap_: null, - byteToCharMapWebSafe_: null, - charToByteMapWebSafe_: null, - ENCODED_VALS_BASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789", - get ENCODED_VALS() { - return this.ENCODED_VALS_BASE + "+/="; - }, - get ENCODED_VALS_WEBSAFE() { - return this.ENCODED_VALS_BASE + "-_."; - }, - HAS_NATIVE_SUPPORT: typeof atob === "function", - encodeByteArray(input, webSafe) { - if (!Array.isArray(input)) { - throw Error("encodeByteArray takes an array as a parameter"); - } - this.init_(); - const byteToCharMap = webSafe ? this.byteToCharMapWebSafe_ : this.byteToCharMap_; - const output = []; - for (let i = 0; i < input.length; i += 3) { - const byte1 = input[i]; - const haveByte2 = i + 1 < input.length; - const byte2 = haveByte2 ? input[i + 1] : 0; - const haveByte3 = i + 2 < input.length; - const byte3 = haveByte3 ? input[i + 2] : 0; - const outByte1 = byte1 >> 2; - const outByte2 = (byte1 & 3) << 4 | byte2 >> 4; - let outByte3 = (byte2 & 15) << 2 | byte3 >> 6; - let outByte4 = byte3 & 63; - if (!haveByte3) { - outByte4 = 64; - if (!haveByte2) { - outByte3 = 64; - } - } - output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); - } - return output.join(""); - }, - encodeString(input, webSafe) { - if (this.HAS_NATIVE_SUPPORT && !webSafe) { - return btoa(input); - } - return this.encodeByteArray(stringToByteArray$1(input), webSafe); - }, - decodeString(input, webSafe) { - if (this.HAS_NATIVE_SUPPORT && !webSafe) { - return atob(input); - } - return byteArrayToString(this.decodeStringToByteArray(input, webSafe)); - }, - decodeStringToByteArray(input, webSafe) { - this.init_(); - const charToByteMap = webSafe ? this.charToByteMapWebSafe_ : this.charToByteMap_; - const output = []; - for (let i = 0; i < input.length; ) { - const byte1 = charToByteMap[input.charAt(i++)]; - const haveByte2 = i < input.length; - const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; - ++i; - const haveByte3 = i < input.length; - const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; - ++i; - const haveByte4 = i < input.length; - const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; - ++i; - if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { - throw new DecodeBase64StringError(); - } - const outByte1 = byte1 << 2 | byte2 >> 4; - output.push(outByte1); - if (byte3 !== 64) { - const outByte2 = byte2 << 4 & 240 | byte3 >> 2; - output.push(outByte2); - if (byte4 !== 64) { - const outByte3 = byte3 << 6 & 192 | byte4; - output.push(outByte3); - } - } - } - return output; - }, - init_() { - if (!this.byteToCharMap_) { - this.byteToCharMap_ = {}; - this.charToByteMap_ = {}; - this.byteToCharMapWebSafe_ = {}; - this.charToByteMapWebSafe_ = {}; - for (let i = 0; i < this.ENCODED_VALS.length; i++) { - this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); - this.charToByteMap_[this.byteToCharMap_[i]] = i; - this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); - this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; - if (i >= this.ENCODED_VALS_BASE.length) { - this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; - this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; - } - } - } - } - }; - class DecodeBase64StringError extends Error { - constructor() { - super(...arguments); - this.name = "DecodeBase64StringError"; - } - } - const base64Encode = function (str) { - const utf8Bytes = stringToByteArray$1(str); - return base64.encodeByteArray(utf8Bytes, true); - }; - const base64urlEncodeWithoutPadding = function (str) { - return base64Encode(str).replace(/\./g, ""); - }; - const base64Decode = function (str) { - try { - return base64.decodeString(str, true); - } catch (e) { - console.error("base64Decode failed: ", e); - } - return null; - }; - function deepCopy(value) { - return deepExtend(undefined, value); - } - function deepExtend(target, source) { - if (!(source instanceof Object)) { - return source; - } - switch (source.constructor) { - case Date: - const dateValue = source; - return new Date(dateValue.getTime()); - case Object: - if (target === undefined) { - target = {}; - } - break; - case Array: - target = []; - break; - default: - return source; - } - for (const prop in source) { - if (!source.hasOwnProperty(prop) || !isValidKey(prop)) { - continue; - } - target[prop] = deepExtend(target[prop], source[prop]); - } - return target; - } - function isValidKey(key) { - return key !== "__proto__"; - } - function getGlobal() { - if (typeof self !== "undefined") { - return self; - } - if (typeof window !== "undefined") { - return window; - } - if (typeof global$1 !== "undefined") { - return global$1; - } - throw new Error("Unable to locate global object."); - } - const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; - const getDefaultsFromEnvVariable = () => { - if (typeof browser$1$1 === "undefined" || typeof browser$1$1.env === "undefined") { - return; - } - const defaultsJsonString = browser$1$1.env.__FIREBASE_DEFAULTS__; - if (defaultsJsonString) { - return JSON.parse(defaultsJsonString); - } - }; - const getDefaultsFromCookie = () => { - if (typeof document === "undefined") { - return; - } - let match; - try { - match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/); - } catch (e) { - return; - } - const decoded = match && base64Decode(match[1]); - return decoded && JSON.parse(decoded); - }; - const getDefaults = () => { - try { - return getDefaultsFromGlobal() || getDefaultsFromEnvVariable() || getDefaultsFromCookie(); - } catch (e) { - console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`); - return; - } - }; - const getDefaultEmulatorHost = productName => { - var _a, _b; - return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; - }; - const getDefaultEmulatorHostnameAndPort = productName => { - const host = getDefaultEmulatorHost(productName); - if (!host) { - return undefined; - } - const separatorIndex = host.lastIndexOf(":"); - if (separatorIndex <= 0 || separatorIndex + 1 === host.length) { - throw new Error(`Invalid host ${host} with no separate hostname and port!`); - } - const port = parseInt(host.substring(separatorIndex + 1), 10); - if (host[0] === "[") { - return [host.substring(1, separatorIndex - 1), port]; - } else { - return [host.substring(0, separatorIndex), port]; - } - }; - const getDefaultAppConfig = () => { - var _a; - return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; - }; - const getExperimentalSetting = name => { - var _a; - return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; - }; - class Deferred { - constructor() { - this.reject = () => {}; - this.resolve = () => {}; - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - } - wrapCallback(callback) { - return (error, value) => { - if (error) { - this.reject(error); - } else { - this.resolve(value); - } - if (typeof callback === "function") { - this.promise.catch(() => {}); - if (callback.length === 1) { - callback(error); - } else { - callback(error, value); - } - } - }; - } - } - function createMockUserToken(token, projectId) { - if (token.uid) { - throw new Error("The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID."); - } - const header = { - alg: "none", - type: "JWT" - }; - const project = projectId || "demo-project"; - const iat = token.iat || 0; - const sub = token.sub || token.user_id; - if (!sub) { - throw new Error("mockUserToken must contain 'sub' or 'user_id' field!"); - } - const payload = Object.assign({ - iss: `https://securetoken.google.com/${project}`, - aud: project, - iat, - exp: iat + 3600, - auth_time: iat, - sub, - user_id: sub, - firebase: { - sign_in_provider: "custom", - identities: {} - } - }, token); - const signature = ""; - return [base64urlEncodeWithoutPadding(JSON.stringify(header)), base64urlEncodeWithoutPadding(JSON.stringify(payload)), signature].join("."); - } - function getUA() { - if (typeof navigator !== "undefined" && typeof navigator["userAgent"] === "string") { - return navigator["userAgent"]; - } else { - return ""; - } - } - function isMobileCordova() { - return typeof window !== "undefined" && !!(window["cordova"] || window["phonegap"] || window["PhoneGap"]) && (/ios|iphone|ipod|ipad|android|blackberry|iemobile/i).test(getUA()); - } - function isNode() { - var _a; - const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment; - if (forceEnvironment === "node") { - return true; - } else if (forceEnvironment === "browser") { - return false; - } - try { - return Object.prototype.toString.call(global$1.process) === "[object process]"; - } catch (e) { - return false; - } - } - function isBrowser() { - return typeof window !== "undefined" || isWebWorker(); - } - function isWebWorker() { - return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope; - } - function isCloudflareWorker() { - return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers"; - } - function isBrowserExtension() { - const runtime = typeof chrome === "object" ? chrome.runtime : typeof browser === "object" ? browser.runtime : undefined; - return typeof runtime === "object" && runtime.id !== undefined; - } - function isReactNative() { - return typeof navigator === "object" && navigator["product"] === "ReactNative"; - } - function isElectron() { - return getUA().indexOf("Electron/") >= 0; - } - function isIE() { - const ua = getUA(); - return ua.indexOf("MSIE ") >= 0 || ua.indexOf("Trident/") >= 0; - } - function isUWP() { - return getUA().indexOf("MSAppHost/") >= 0; - } - function isNodeSdk() { - return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; - } - function isSafari() { - return !isNode() && !!navigator.userAgent && navigator.userAgent.includes("Safari") && !navigator.userAgent.includes("Chrome"); - } - function isIndexedDBAvailable() { - try { - return typeof indexedDB === "object"; - } catch (e) { - return false; - } - } - function validateIndexedDBOpenable() { - return new Promise((resolve, reject) => { - try { - let preExist = true; - const DB_CHECK_NAME = "validate-browser-context-for-indexeddb-analytics-module"; - const request = self.indexedDB.open(DB_CHECK_NAME); - request.onsuccess = () => { - request.result.close(); - if (!preExist) { - self.indexedDB.deleteDatabase(DB_CHECK_NAME); - } - resolve(true); - }; - request.onupgradeneeded = () => { - preExist = false; - }; - request.onerror = () => { - var _a; - reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || ""); - }; - } catch (error) { - reject(error); - } - }); - } - function areCookiesEnabled() { - if (typeof navigator === "undefined" || !navigator.cookieEnabled) { - return false; - } - return true; - } - const ERROR_NAME = "FirebaseError"; - class FirebaseError extends Error { - constructor(code, message, customData) { - super(message); - this.code = code; - this.customData = customData; - this.name = ERROR_NAME; - Object.setPrototypeOf(this, FirebaseError.prototype); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, ErrorFactory.prototype.create); - } - } - } - class ErrorFactory { - constructor(service, serviceName, errors) { - this.service = service; - this.serviceName = serviceName; - this.errors = errors; - } - create(code, ...data) { - const customData = data[0] || ({}); - const fullCode = `${this.service}/${code}`; - const template = this.errors[code]; - const message = template ? replaceTemplate(template, customData) : "Error"; - const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; - const error = new FirebaseError(fullCode, fullMessage, customData); - return error; - } - } - function replaceTemplate(template, data) { - return template.replace(PATTERN, (_, key) => { - const value = data[key]; - return value != null ? String(value) : `<${key}?>`; - }); - } - const PATTERN = /\{\$([^}]+)}/g; - function jsonEval(str) { - return JSON.parse(str); - } - function stringify(data) { - return JSON.stringify(data); - } - const decode = function (token) { - let header = {}, claims = {}, data = {}, signature = ""; - try { - const parts = token.split("."); - header = jsonEval(base64Decode(parts[0]) || ""); - claims = jsonEval(base64Decode(parts[1]) || ""); - signature = parts[2]; - data = claims["d"] || ({}); - delete claims["d"]; - } catch (e) {} - return { - header, - claims, - data, - signature - }; - }; - const isValidTimestamp = function (token) { - const claims = decode(token).claims; - const now = Math.floor(new Date().getTime() / 1000); - let validSince = 0, validUntil = 0; - if (typeof claims === "object") { - if (claims.hasOwnProperty("nbf")) { - validSince = claims["nbf"]; - } else if (claims.hasOwnProperty("iat")) { - validSince = claims["iat"]; - } - if (claims.hasOwnProperty("exp")) { - validUntil = claims["exp"]; - } else { - validUntil = validSince + 86400; - } - } - return !!now && !!validSince && !!validUntil && now >= validSince && now <= validUntil; - }; - const issuedAtTime = function (token) { - const claims = decode(token).claims; - if (typeof claims === "object" && claims.hasOwnProperty("iat")) { - return claims["iat"]; - } - return null; - }; - const isValidFormat = function (token) { - const decoded = decode(token), claims = decoded.claims; - return !!claims && typeof claims === "object" && claims.hasOwnProperty("iat"); - }; - const isAdmin = function (token) { - const claims = decode(token).claims; - return typeof claims === "object" && claims["admin"] === true; - }; - function contains(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); - } - function safeGet(obj, key) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - return obj[key]; - } else { - return undefined; - } - } - function isEmpty(obj) { - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - return false; - } - } - return true; - } - function map(obj, fn, contextObj) { - const res = {}; - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - res[key] = fn.call(contextObj, obj[key], key, obj); - } - } - return res; - } - function deepEqual(a, b) { - if (a === b) { - return true; - } - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - for (const k of aKeys) { - if (!bKeys.includes(k)) { - return false; - } - const aProp = a[k]; - const bProp = b[k]; - if (isObject(aProp) && isObject(bProp)) { - if (!deepEqual(aProp, bProp)) { - return false; - } - } else if (aProp !== bProp) { - return false; - } - } - for (const k of bKeys) { - if (!aKeys.includes(k)) { - return false; - } - } - return true; - } - function isObject(thing) { - return thing !== null && typeof thing === "object"; - } - function promiseWithTimeout(promise, timeInMS = 2000) { - const deferredPromise = new Deferred(); - setTimeout(() => deferredPromise.reject("timeout!"), timeInMS); - promise.then(deferredPromise.resolve, deferredPromise.reject); - return deferredPromise.promise; - } - function querystring(querystringParams) { - const params = []; - for (const [key, value] of Object.entries(querystringParams)) { - if (Array.isArray(value)) { - value.forEach(arrayVal => { - params.push(encodeURIComponent(key) + "=" + encodeURIComponent(arrayVal)); - }); - } else { - params.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); - } - } - return params.length ? "&" + params.join("&") : ""; - } - function querystringDecode(querystring) { - const obj = {}; - const tokens = querystring.replace(/^\?/, "").split("&"); - tokens.forEach(token => { - if (token) { - const [key, value] = token.split("="); - obj[decodeURIComponent(key)] = decodeURIComponent(value); - } - }); - return obj; - } - function extractQuerystring(url) { - const queryStart = url.indexOf("?"); - if (!queryStart) { - return ""; - } - const fragmentStart = url.indexOf("#", queryStart); - return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined); - } - class Sha1 { - constructor() { - this.chain_ = []; - this.buf_ = []; - this.W_ = []; - this.pad_ = []; - this.inbuf_ = 0; - this.total_ = 0; - this.blockSize = 512 / 8; - this.pad_[0] = 128; - for (let i = 1; i < this.blockSize; ++i) { - this.pad_[i] = 0; - } - this.reset(); - } - reset() { - this.chain_[0] = 1732584193; - this.chain_[1] = 4023233417; - this.chain_[2] = 2562383102; - this.chain_[3] = 271733878; - this.chain_[4] = 3285377520; - this.inbuf_ = 0; - this.total_ = 0; - } - compress_(buf, offset) { - if (!offset) { - offset = 0; - } - const W = this.W_; - if (typeof buf === "string") { - for (let i = 0; i < 16; i++) { - W[i] = buf.charCodeAt(offset) << 24 | buf.charCodeAt(offset + 1) << 16 | buf.charCodeAt(offset + 2) << 8 | buf.charCodeAt(offset + 3); - offset += 4; - } - } else { - for (let i = 0; i < 16; i++) { - W[i] = buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3]; - offset += 4; - } - } - for (let i = 16; i < 80; i++) { - const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = (t << 1 | t >>> 31) & 4294967295; - } - let a = this.chain_[0]; - let b = this.chain_[1]; - let c = this.chain_[2]; - let d = this.chain_[3]; - let e = this.chain_[4]; - let f, k; - for (let i = 0; i < 80; i++) { - if (i < 40) { - if (i < 20) { - f = d ^ b & (c ^ d); - k = 1518500249; - } else { - f = b ^ c ^ d; - k = 1859775393; - } - } else { - if (i < 60) { - f = b & c | d & (b | c); - k = 2400959708; - } else { - f = b ^ c ^ d; - k = 3395469782; - } - } - const t = (a << 5 | a >>> 27) + f + e + k + W[i] & 4294967295; - e = d; - d = c; - c = (b << 30 | b >>> 2) & 4294967295; - b = a; - a = t; - } - this.chain_[0] = this.chain_[0] + a & 4294967295; - this.chain_[1] = this.chain_[1] + b & 4294967295; - this.chain_[2] = this.chain_[2] + c & 4294967295; - this.chain_[3] = this.chain_[3] + d & 4294967295; - this.chain_[4] = this.chain_[4] + e & 4294967295; - } - update(bytes, length) { - if (bytes == null) { - return; - } - if (length === undefined) { - length = bytes.length; - } - const lengthMinusBlock = length - this.blockSize; - let n = 0; - const buf = this.buf_; - let inbuf = this.inbuf_; - while (n < length) { - if (inbuf === 0) { - while (n <= lengthMinusBlock) { - this.compress_(bytes, n); - n += this.blockSize; - } - } - if (typeof bytes === "string") { - while (n < length) { - buf[inbuf] = bytes.charCodeAt(n); - ++inbuf; - ++n; - if (inbuf === this.blockSize) { - this.compress_(buf); - inbuf = 0; - break; - } - } - } else { - while (n < length) { - buf[inbuf] = bytes[n]; - ++inbuf; - ++n; - if (inbuf === this.blockSize) { - this.compress_(buf); - inbuf = 0; - break; - } - } - } - } - this.inbuf_ = inbuf; - this.total_ += length; - } - digest() { - const digest = []; - let totalBits = this.total_ * 8; - if (this.inbuf_ < 56) { - this.update(this.pad_, 56 - this.inbuf_); - } else { - this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); - } - for (let i = this.blockSize - 1; i >= 56; i--) { - this.buf_[i] = totalBits & 255; - totalBits /= 256; - } - this.compress_(this.buf_); - let n = 0; - for (let i = 0; i < 5; i++) { - for (let j = 24; j >= 0; j -= 8) { - digest[n] = this.chain_[i] >> j & 255; - ++n; - } - } - return digest; - } - } - function createSubscribe(executor, onNoObservers) { - const proxy = new ObserverProxy(executor, onNoObservers); - return proxy.subscribe.bind(proxy); - } - class ObserverProxy { - constructor(executor, onNoObservers) { - this.observers = []; - this.unsubscribes = []; - this.observerCount = 0; - this.task = Promise.resolve(); - this.finalized = false; - this.onNoObservers = onNoObservers; - this.task.then(() => { - executor(this); - }).catch(e => { - this.error(e); - }); - } - next(value) { - this.forEachObserver(observer => { - observer.next(value); - }); - } - error(error) { - this.forEachObserver(observer => { - observer.error(error); - }); - this.close(error); - } - complete() { - this.forEachObserver(observer => { - observer.complete(); - }); - this.close(); - } - subscribe(nextOrObserver, error, complete) { - let observer; - if (nextOrObserver === undefined && error === undefined && complete === undefined) { - throw new Error("Missing Observer."); - } - if (implementsAnyMethods(nextOrObserver, ["next", "error", "complete"])) { - observer = nextOrObserver; - } else { - observer = { - next: nextOrObserver, - error, - complete - }; - } - if (observer.next === undefined) { - observer.next = noop; - } - if (observer.error === undefined) { - observer.error = noop; - } - if (observer.complete === undefined) { - observer.complete = noop; - } - const unsub = this.unsubscribeOne.bind(this, this.observers.length); - if (this.finalized) { - this.task.then(() => { - try { - if (this.finalError) { - observer.error(this.finalError); - } else { - observer.complete(); - } - } catch (e) {} - return; - }); - } - this.observers.push(observer); - return unsub; - } - unsubscribeOne(i) { - if (this.observers === undefined || this.observers[i] === undefined) { - return; - } - delete this.observers[i]; - this.observerCount -= 1; - if (this.observerCount === 0 && this.onNoObservers !== undefined) { - this.onNoObservers(this); - } - } - forEachObserver(fn) { - if (this.finalized) { - return; - } - for (let i = 0; i < this.observers.length; i++) { - this.sendOne(i, fn); - } - } - sendOne(i, fn) { - this.task.then(() => { - if (this.observers !== undefined && this.observers[i] !== undefined) { - try { - fn(this.observers[i]); - } catch (e) { - if (typeof console !== "undefined" && console.error) { - console.error(e); - } - } - } - }); - } - close(err) { - if (this.finalized) { - return; - } - this.finalized = true; - if (err !== undefined) { - this.finalError = err; - } - this.task.then(() => { - this.observers = undefined; - this.onNoObservers = undefined; - }); - } - } - function async(fn, onError) { - return (...args) => { - Promise.resolve(true).then(() => { - fn(...args); - }).catch(error => { - if (onError) { - onError(error); - } - }); - }; - } - function implementsAnyMethods(obj, methods) { - if (typeof obj !== "object" || obj === null) { - return false; - } - for (const method of methods) { - if ((method in obj) && typeof obj[method] === "function") { - return true; - } - } - return false; - } - function noop() {} - const validateArgCount = function (fnName, minCount, maxCount, argCount) { - let argError; - if (argCount < minCount) { - argError = "at least " + minCount; - } else if (argCount > maxCount) { - argError = maxCount === 0 ? "none" : "no more than " + maxCount; - } - if (argError) { - const error = fnName + " failed: Was called with " + argCount + (argCount === 1 ? " argument." : " arguments.") + " Expects " + argError + "."; - throw new Error(error); - } - }; - function errorPrefix(fnName, argName) { - return `${fnName} failed: ${argName} argument `; - } - function validateNamespace(fnName, namespace, optional) { - if (optional && !namespace) { - return; - } - if (typeof namespace !== "string") { - throw new Error(errorPrefix(fnName, "namespace") + "must be a valid firebase namespace."); - } - } - function validateCallback(fnName, argumentName, callback, optional) { - if (optional && !callback) { - return; - } - if (typeof callback !== "function") { - throw new Error(errorPrefix(fnName, argumentName) + "must be a valid function."); - } - } - function validateContextObject(fnName, argumentName, context, optional) { - if (optional && !context) { - return; - } - if (typeof context !== "object" || context === null) { - throw new Error(errorPrefix(fnName, argumentName) + "must be a valid context object."); - } - } - const stringToByteArray = function (str) { - const out = []; - let p = 0; - for (let i = 0; i < str.length; i++) { - let c = str.charCodeAt(i); - if (c >= 55296 && c <= 56319) { - const high = c - 55296; - i++; - assert(i < str.length, "Surrogate pair missing trail surrogate."); - const low = str.charCodeAt(i) - 56320; - c = 65536 + (high << 10) + low; - } - if (c < 128) { - out[p++] = c; - } else if (c < 2048) { - out[p++] = c >> 6 | 192; - out[p++] = c & 63 | 128; - } else if (c < 65536) { - out[p++] = c >> 12 | 224; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; - } else { - out[p++] = c >> 18 | 240; - out[p++] = c >> 12 & 63 | 128; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; - } - } - return out; - }; - const stringLength = function (str) { - let p = 0; - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - if (c < 128) { - p++; - } else if (c < 2048) { - p += 2; - } else if (c >= 55296 && c <= 56319) { - p += 4; - i++; - } else { - p += 3; - } - } - return p; - }; - const uuidv4 = function () { - return ("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx").replace(/[xy]/g, c => { - const r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8; - return v.toString(16); - }); - }; - const DEFAULT_INTERVAL_MILLIS = 1000; - const DEFAULT_BACKOFF_FACTOR = 2; - const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; - const RANDOM_FACTOR = 0.5; - function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) { - const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount); - const randomWait = Math.round(RANDOM_FACTOR * currBaseValue * (Math.random() - 0.5) * 2); - return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait); - } - function ordinal(i) { - if (!Number.isFinite(i)) { - return `${i}`; - } - return i + indicator(i); - } - function indicator(i) { - i = Math.abs(i); - const cent = i % 100; - if (cent >= 10 && cent <= 20) { - return "th"; - } - const dec = i % 10; - if (dec === 1) { - return "st"; - } - if (dec === 2) { - return "nd"; - } - if (dec === 3) { - return "rd"; - } - return "th"; - } - function getModularInstance(service) { - if (service && service._delegate) { - return service._delegate; - } else { - return service; - } - } - - var index_esm2017 = /*#__PURE__*/Object.freeze({ - __proto__: null, - CONSTANTS: CONSTANTS, - DecodeBase64StringError: DecodeBase64StringError, - Deferred: Deferred, - ErrorFactory: ErrorFactory, - FirebaseError: FirebaseError, - MAX_VALUE_MILLIS: MAX_VALUE_MILLIS, - RANDOM_FACTOR: RANDOM_FACTOR, - Sha1: Sha1, - areCookiesEnabled: areCookiesEnabled, - assert: assert, - assertionError: assertionError, - async: async, - base64: base64, - base64Decode: base64Decode, - base64Encode: base64Encode, - base64urlEncodeWithoutPadding: base64urlEncodeWithoutPadding, - calculateBackoffMillis: calculateBackoffMillis, - contains: contains, - createMockUserToken: createMockUserToken, - createSubscribe: createSubscribe, - decode: decode, - deepCopy: deepCopy, - deepEqual: deepEqual, - deepExtend: deepExtend, - errorPrefix: errorPrefix, - extractQuerystring: extractQuerystring, - getDefaultAppConfig: getDefaultAppConfig, - getDefaultEmulatorHost: getDefaultEmulatorHost, - getDefaultEmulatorHostnameAndPort: getDefaultEmulatorHostnameAndPort, - getDefaults: getDefaults, - getExperimentalSetting: getExperimentalSetting, - getGlobal: getGlobal, - getModularInstance: getModularInstance, - getUA: getUA, - isAdmin: isAdmin, - isBrowser: isBrowser, - isBrowserExtension: isBrowserExtension, - isCloudflareWorker: isCloudflareWorker, - isElectron: isElectron, - isEmpty: isEmpty, - isIE: isIE, - isIndexedDBAvailable: isIndexedDBAvailable, - isMobileCordova: isMobileCordova, - isNode: isNode, - isNodeSdk: isNodeSdk, - isReactNative: isReactNative, - isSafari: isSafari, - isUWP: isUWP, - isValidFormat: isValidFormat, - isValidTimestamp: isValidTimestamp, - isWebWorker: isWebWorker, - issuedAtTime: issuedAtTime, - jsonEval: jsonEval, - map: map, - ordinal: ordinal, - promiseWithTimeout: promiseWithTimeout, - querystring: querystring, - querystringDecode: querystringDecode, - safeGet: safeGet, - stringLength: stringLength, - stringToByteArray: stringToByteArray, - stringify: stringify, - uuidv4: uuidv4, - validateArgCount: validateArgCount, - validateCallback: validateCallback, - validateContextObject: validateContextObject, - validateIndexedDBOpenable: validateIndexedDBOpenable, - validateNamespace: validateNamespace - }); - - var require$$4 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); - - Object.defineProperty(index_cjs$1, '__esModule', { value: true }); - - var util = require$$4; - - /** - * Component for service name T, e.g. `auth`, `auth-internal` - */ - class Component { - /** - * - * @param name The public service name, e.g. app, auth, firestore, database - * @param instanceFactory Service factory responsible for creating the public interface - * @param type whether the service provided by the component is public or private - */ - constructor(name, instanceFactory, type) { - this.name = name; - this.instanceFactory = instanceFactory; - this.type = type; - this.multipleInstances = false; - /** - * Properties to be added to the service namespace - */ - this.serviceProps = {}; - this.instantiationMode = "LAZY" /* InstantiationMode.LAZY */; - this.onInstanceCreated = null; - } - setInstantiationMode(mode) { - this.instantiationMode = mode; - return this; - } - setMultipleInstances(multipleInstances) { - this.multipleInstances = multipleInstances; - return this; - } - setServiceProps(props) { - this.serviceProps = props; - return this; - } - setInstanceCreatedCallback(callback) { - this.onInstanceCreated = callback; - return this; - } - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - const DEFAULT_ENTRY_NAME = '[DEFAULT]'; - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - /** - * Provider for instance for service name T, e.g. 'auth', 'auth-internal' - * NameServiceMapping[T] is an alias for the type of the instance - */ - class Provider { - constructor(name, container) { - this.name = name; - this.container = container; - this.component = null; - this.instances = new Map(); - this.instancesDeferred = new Map(); - this.instancesOptions = new Map(); - this.onInitCallbacks = new Map(); - } - /** - * @param identifier A provider can provide multiple instances of a service - * if this.component.multipleInstances is true. - */ - get(identifier) { - // if multipleInstances is not supported, use the default name - const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); - if (!this.instancesDeferred.has(normalizedIdentifier)) { - const deferred = new util.Deferred(); - this.instancesDeferred.set(normalizedIdentifier, deferred); - if (this.isInitialized(normalizedIdentifier) || - this.shouldAutoInitialize()) { - // initialize the service if it can be auto-initialized - try { - const instance = this.getOrInitializeService({ - instanceIdentifier: normalizedIdentifier - }); - if (instance) { - deferred.resolve(instance); - } - } - catch (e) { - // when the instance factory throws an exception during get(), it should not cause - // a fatal error. We just return the unresolved promise in this case. - } - } - } - return this.instancesDeferred.get(normalizedIdentifier).promise; - } - getImmediate(options) { - var _a; - // if multipleInstances is not supported, use the default name - const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); - const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false; - if (this.isInitialized(normalizedIdentifier) || - this.shouldAutoInitialize()) { - try { - return this.getOrInitializeService({ - instanceIdentifier: normalizedIdentifier - }); - } - catch (e) { - if (optional) { - return null; - } - else { - throw e; - } - } - } - else { - // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw - if (optional) { - return null; - } - else { - throw Error(`Service ${this.name} is not available`); - } - } - } - getComponent() { - return this.component; - } - setComponent(component) { - if (component.name !== this.name) { - throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`); - } - if (this.component) { - throw Error(`Component for ${this.name} has already been provided`); - } - this.component = component; - // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) - if (!this.shouldAutoInitialize()) { - return; - } - // if the service is eager, initialize the default instance - if (isComponentEager(component)) { - try { - this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); - } - catch (e) { - // when the instance factory for an eager Component throws an exception during the eager - // initialization, it should not cause a fatal error. - // TODO: Investigate if we need to make it configurable, because some component may want to cause - // a fatal error in this case? - } - } - // Create service instances for the pending promises and resolve them - // NOTE: if this.multipleInstances is false, only the default instance will be created - // and all promises with resolve with it regardless of the identifier. - for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { - const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); - try { - // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. - const instance = this.getOrInitializeService({ - instanceIdentifier: normalizedIdentifier - }); - instanceDeferred.resolve(instance); - } - catch (e) { - // when the instance factory throws an exception, it should not cause - // a fatal error. We just leave the promise unresolved. - } - } - } - clearInstance(identifier = DEFAULT_ENTRY_NAME) { - this.instancesDeferred.delete(identifier); - this.instancesOptions.delete(identifier); - this.instances.delete(identifier); - } - // app.delete() will call this method on every provider to delete the services - // TODO: should we mark the provider as deleted? - async delete() { - const services = Array.from(this.instances.values()); - await Promise.all([ - ...services - .filter(service => 'INTERNAL' in service) // legacy services - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .map(service => service.INTERNAL.delete()), - ...services - .filter(service => '_delete' in service) // modularized services - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .map(service => service._delete()) - ]); - } - isComponentSet() { - return this.component != null; - } - isInitialized(identifier = DEFAULT_ENTRY_NAME) { - return this.instances.has(identifier); - } - getOptions(identifier = DEFAULT_ENTRY_NAME) { - return this.instancesOptions.get(identifier) || {}; - } - initialize(opts = {}) { - const { options = {} } = opts; - const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); - if (this.isInitialized(normalizedIdentifier)) { - throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`); - } - if (!this.isComponentSet()) { - throw Error(`Component ${this.name} has not been registered yet`); - } - const instance = this.getOrInitializeService({ - instanceIdentifier: normalizedIdentifier, - options - }); - // resolve any pending promise waiting for the service instance - for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { - const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); - if (normalizedIdentifier === normalizedDeferredIdentifier) { - instanceDeferred.resolve(instance); - } - } - return instance; - } - /** - * - * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). - * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. - * - * @param identifier An optional instance identifier - * @returns a function to unregister the callback - */ - onInit(callback, identifier) { - var _a; - const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); - const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); - existingCallbacks.add(callback); - this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); - const existingInstance = this.instances.get(normalizedIdentifier); - if (existingInstance) { - callback(existingInstance, normalizedIdentifier); - } - return () => { - existingCallbacks.delete(callback); - }; - } - /** - * Invoke onInit callbacks synchronously - * @param instance the service instance` - */ - invokeOnInitCallbacks(instance, identifier) { - const callbacks = this.onInitCallbacks.get(identifier); - if (!callbacks) { - return; - } - for (const callback of callbacks) { - try { - callback(instance, identifier); - } - catch (_a) { - // ignore errors in the onInit callback - } - } - } - getOrInitializeService({ instanceIdentifier, options = {} }) { - let instance = this.instances.get(instanceIdentifier); - if (!instance && this.component) { - instance = this.component.instanceFactory(this.container, { - instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), - options - }); - this.instances.set(instanceIdentifier, instance); - this.instancesOptions.set(instanceIdentifier, options); - /** - * Invoke onInit listeners. - * Note this.component.onInstanceCreated is different, which is used by the component creator, - * while onInit listeners are registered by consumers of the provider. - */ - this.invokeOnInitCallbacks(instance, instanceIdentifier); - /** - * Order is important - * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which - * makes `isInitialized()` return true. - */ - if (this.component.onInstanceCreated) { - try { - this.component.onInstanceCreated(this.container, instanceIdentifier, instance); - } - catch (_a) { - // ignore errors in the onInstanceCreatedCallback - } - } - } - return instance || null; - } - normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) { - if (this.component) { - return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; - } - else { - return identifier; // assume multiple instances are supported before the component is provided. - } - } - shouldAutoInitialize() { - return (!!this.component && - this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */); - } - } - // undefined should be passed to the service factory for the default instance - function normalizeIdentifierForFactory(identifier) { - return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier; - } - function isComponentEager(component) { - return component.instantiationMode === "EAGER" /* InstantiationMode.EAGER */; - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - /** - * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` - */ - class ComponentContainer { - constructor(name) { - this.name = name; - this.providers = new Map(); - } - /** - * - * @param component Component being added - * @param overwrite When a component with the same name has already been registered, - * if overwrite is true: overwrite the existing component with the new component and create a new - * provider with the new component. It can be useful in tests where you want to use different mocks - * for different tests. - * if overwrite is false: throw an exception - */ - addComponent(component) { - const provider = this.getProvider(component.name); - if (provider.isComponentSet()) { - throw new Error(`Component ${component.name} has already been registered with ${this.name}`); - } - provider.setComponent(component); - } - addOrOverwriteComponent(component) { - const provider = this.getProvider(component.name); - if (provider.isComponentSet()) { - // delete the existing provider from the container, so we can register the new component - this.providers.delete(component.name); - } - this.addComponent(component); - } - /** - * getProvider provides a type safe interface where it can only be called with a field name - * present in NameServiceMapping interface. - * - * Firebase SDKs providing services should extend NameServiceMapping interface to register - * themselves. - */ - getProvider(name) { - if (this.providers.has(name)) { - return this.providers.get(name); - } - // create a Provider for a service that hasn't registered with Firebase - const provider = new Provider(name, this); - this.providers.set(name, provider); - return provider; - } - getProviders() { - return Array.from(this.providers.values()); - } - } - - index_cjs$1.Component = Component; - index_cjs$1.ComponentContainer = ComponentContainer; - index_cjs$1.Provider = Provider; - - var index_cjs = {}; - - (function (exports) { - - Object.defineProperty(exports, '__esModule', { value: true }); - - /** - * @license - * Copyright 2017 Google LLC - * - * 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. - */ - /** - * A container for all of the Logger instances - */ - const instances = []; - /** - * The JS SDK supports 5 log levels and also allows a user the ability to - * silence the logs altogether. - * - * The order is a follows: - * DEBUG < VERBOSE < INFO < WARN < ERROR - * - * All of the log types above the current log level will be captured (i.e. if - * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and - * `VERBOSE` logs will not) - */ - exports.LogLevel = void 0; - (function (LogLevel) { - LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; - LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; - LogLevel[LogLevel["INFO"] = 2] = "INFO"; - LogLevel[LogLevel["WARN"] = 3] = "WARN"; - LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; - LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; - })(exports.LogLevel || (exports.LogLevel = {})); - const levelStringToEnum = { - 'debug': exports.LogLevel.DEBUG, - 'verbose': exports.LogLevel.VERBOSE, - 'info': exports.LogLevel.INFO, - 'warn': exports.LogLevel.WARN, - 'error': exports.LogLevel.ERROR, - 'silent': exports.LogLevel.SILENT - }; - /** - * The default log level - */ - const defaultLogLevel = exports.LogLevel.INFO; - /** - * By default, `console.debug` is not displayed in the developer console (in - * chrome). To avoid forcing users to have to opt-in to these logs twice - * (i.e. once for firebase, and once in the console), we are sending `DEBUG` - * logs to the `console.log` function. - */ - const ConsoleMethod = { - [exports.LogLevel.DEBUG]: 'log', - [exports.LogLevel.VERBOSE]: 'log', - [exports.LogLevel.INFO]: 'info', - [exports.LogLevel.WARN]: 'warn', - [exports.LogLevel.ERROR]: 'error' - }; - /** - * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR - * messages on to their corresponding console counterparts (if the log method - * is supported by the current log level) - */ - const defaultLogHandler = (instance, logType, ...args) => { - if (logType < instance.logLevel) { - return; - } - const now = new Date().toISOString(); - const method = ConsoleMethod[logType]; - if (method) { - console[method](`[${now}] ${instance.name}:`, ...args); - } - else { - throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`); - } - }; - class Logger { - /** - * Gives you an instance of a Logger to capture messages according to - * Firebase's logging scheme. - * - * @param name The name that the logs will be associated with - */ - constructor(name) { - this.name = name; - /** - * The log level of the given Logger instance. - */ - this._logLevel = defaultLogLevel; - /** - * The main (internal) log handler for the Logger instance. - * Can be set to a new function in internal package code but not by user. - */ - this._logHandler = defaultLogHandler; - /** - * The optional, additional, user-defined log handler for the Logger instance. - */ - this._userLogHandler = null; - /** - * Capture the current instance for later use - */ - instances.push(this); - } - get logLevel() { - return this._logLevel; - } - set logLevel(val) { - if (!(val in exports.LogLevel)) { - throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``); - } - this._logLevel = val; - } - // Workaround for setter/getter having to be the same type. - setLogLevel(val) { - this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; - } - get logHandler() { - return this._logHandler; - } - set logHandler(val) { - if (typeof val !== 'function') { - throw new TypeError('Value assigned to `logHandler` must be a function'); - } - this._logHandler = val; - } - get userLogHandler() { - return this._userLogHandler; - } - set userLogHandler(val) { - this._userLogHandler = val; - } - /** - * The functions below are all based on the `console` interface - */ - debug(...args) { - this._userLogHandler && this._userLogHandler(this, exports.LogLevel.DEBUG, ...args); - this._logHandler(this, exports.LogLevel.DEBUG, ...args); - } - log(...args) { - this._userLogHandler && - this._userLogHandler(this, exports.LogLevel.VERBOSE, ...args); - this._logHandler(this, exports.LogLevel.VERBOSE, ...args); - } - info(...args) { - this._userLogHandler && this._userLogHandler(this, exports.LogLevel.INFO, ...args); - this._logHandler(this, exports.LogLevel.INFO, ...args); - } - warn(...args) { - this._userLogHandler && this._userLogHandler(this, exports.LogLevel.WARN, ...args); - this._logHandler(this, exports.LogLevel.WARN, ...args); - } - error(...args) { - this._userLogHandler && this._userLogHandler(this, exports.LogLevel.ERROR, ...args); - this._logHandler(this, exports.LogLevel.ERROR, ...args); - } - } - function setLogLevel(level) { - instances.forEach(inst => { - inst.setLogLevel(level); - }); - } - function setUserLogHandler(logCallback, options) { - for (const instance of instances) { - let customLogLevel = null; - if (options && options.level) { - customLogLevel = levelStringToEnum[options.level]; - } - if (logCallback === null) { - instance.userLogHandler = null; - } - else { - instance.userLogHandler = (instance, level, ...args) => { - const message = args - .map(arg => { - if (arg == null) { - return null; - } - else if (typeof arg === 'string') { - return arg; - } - else if (typeof arg === 'number' || typeof arg === 'boolean') { - return arg.toString(); - } - else if (arg instanceof Error) { - return arg.message; - } - else { - try { - return JSON.stringify(arg); - } - catch (ignored) { - return null; - } - } - }) - .filter(arg => arg) - .join(' '); - if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) { - logCallback({ - level: exports.LogLevel[level].toLowerCase(), - message, - args, - type: instance.name - }); - } - }; - } - } - } - - exports.Logger = Logger; - exports.setLogLevel = setLogLevel; - exports.setUserLogHandler = setUserLogHandler; - - } (index_cjs)); - - const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); - - let idbProxyableTypes; - let cursorAdvanceMethods; - // This is a function to prevent it throwing up in node environments. - function getIdbProxyableTypes() { - return (idbProxyableTypes || - (idbProxyableTypes = [ - IDBDatabase, - IDBObjectStore, - IDBIndex, - IDBCursor, - IDBTransaction, - ])); - } - // This is a function to prevent it throwing up in node environments. - function getCursorAdvanceMethods() { - return (cursorAdvanceMethods || - (cursorAdvanceMethods = [ - IDBCursor.prototype.advance, - IDBCursor.prototype.continue, - IDBCursor.prototype.continuePrimaryKey, - ])); - } - const cursorRequestMap = new WeakMap(); - const transactionDoneMap = new WeakMap(); - const transactionStoreNamesMap = new WeakMap(); - const transformCache = new WeakMap(); - const reverseTransformCache = new WeakMap(); - function promisifyRequest(request) { - const promise = new Promise((resolve, reject) => { - const unlisten = () => { - request.removeEventListener('success', success); - request.removeEventListener('error', error); - }; - const success = () => { - resolve(wrap(request.result)); - unlisten(); - }; - const error = () => { - reject(request.error); - unlisten(); - }; - request.addEventListener('success', success); - request.addEventListener('error', error); - }); - promise - .then((value) => { - // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval - // (see wrapFunction). - if (value instanceof IDBCursor) { - cursorRequestMap.set(value, request); - } - // Catching to avoid "Uncaught Promise exceptions" - }) - .catch(() => { }); - // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This - // is because we create many promises from a single IDBRequest. - reverseTransformCache.set(promise, request); - return promise; - } - function cacheDonePromiseForTransaction(tx) { - // Early bail if we've already created a done promise for this transaction. - if (transactionDoneMap.has(tx)) - return; - const done = new Promise((resolve, reject) => { - const unlisten = () => { - tx.removeEventListener('complete', complete); - tx.removeEventListener('error', error); - tx.removeEventListener('abort', error); - }; - const complete = () => { - resolve(); - unlisten(); - }; - const error = () => { - reject(tx.error || new DOMException('AbortError', 'AbortError')); - unlisten(); - }; - tx.addEventListener('complete', complete); - tx.addEventListener('error', error); - tx.addEventListener('abort', error); - }); - // Cache it for later retrieval. - transactionDoneMap.set(tx, done); - } - let idbProxyTraps = { - get(target, prop, receiver) { - if (target instanceof IDBTransaction) { - // Special handling for transaction.done. - if (prop === 'done') - return transactionDoneMap.get(target); - // Polyfill for objectStoreNames because of Edge. - if (prop === 'objectStoreNames') { - return target.objectStoreNames || transactionStoreNamesMap.get(target); - } - // Make tx.store return the only store in the transaction, or undefined if there are many. - if (prop === 'store') { - return receiver.objectStoreNames[1] - ? undefined - : receiver.objectStore(receiver.objectStoreNames[0]); - } - } - // Else transform whatever we get back. - return wrap(target[prop]); - }, - set(target, prop, value) { - target[prop] = value; - return true; - }, - has(target, prop) { - if (target instanceof IDBTransaction && - (prop === 'done' || prop === 'store')) { - return true; - } - return prop in target; - }, - }; - function replaceTraps(callback) { - idbProxyTraps = callback(idbProxyTraps); - } - function wrapFunction(func) { - // Due to expected object equality (which is enforced by the caching in `wrap`), we - // only create one new func per func. - // Edge doesn't support objectStoreNames (booo), so we polyfill it here. - if (func === IDBDatabase.prototype.transaction && - !('objectStoreNames' in IDBTransaction.prototype)) { - return function (storeNames, ...args) { - const tx = func.call(unwrap(this), storeNames, ...args); - transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); - return wrap(tx); - }; - } - // Cursor methods are special, as the behaviour is a little more different to standard IDB. In - // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the - // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense - // with real promises, so each advance methods returns a new promise for the cursor object, or - // undefined if the end of the cursor has been reached. - if (getCursorAdvanceMethods().includes(func)) { - return function (...args) { - // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use - // the original object. - func.apply(unwrap(this), args); - return wrap(cursorRequestMap.get(this)); - }; - } - return function (...args) { - // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use - // the original object. - return wrap(func.apply(unwrap(this), args)); - }; - } - function transformCachableValue(value) { - if (typeof value === 'function') - return wrapFunction(value); - // This doesn't return, it just creates a 'done' promise for the transaction, - // which is later returned for transaction.done (see idbObjectHandler). - if (value instanceof IDBTransaction) - cacheDonePromiseForTransaction(value); - if (instanceOfAny(value, getIdbProxyableTypes())) - return new Proxy(value, idbProxyTraps); - // Return the same value back if we're not going to transform it. - return value; - } - function wrap(value) { - // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because - // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. - if (value instanceof IDBRequest) - return promisifyRequest(value); - // If we've already transformed this value before, reuse the transformed value. - // This is faster, but it also provides object equality. - if (transformCache.has(value)) - return transformCache.get(value); - const newValue = transformCachableValue(value); - // Not all types are transformed. - // These may be primitive types, so they can't be WeakMap keys. - if (newValue !== value) { - transformCache.set(value, newValue); - reverseTransformCache.set(newValue, value); - } - return newValue; - } - const unwrap = (value) => reverseTransformCache.get(value); - - /** - * Open a database. - * - * @param name Name of the database. - * @param version Schema version. - * @param callbacks Additional callbacks. - */ - function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { - const request = indexedDB.open(name, version); - const openPromise = wrap(request); - if (upgrade) { - request.addEventListener('upgradeneeded', (event) => { - upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); - }); - } - if (blocked) { - request.addEventListener('blocked', (event) => blocked( - // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 - event.oldVersion, event.newVersion, event)); - } - openPromise - .then((db) => { - if (terminated) - db.addEventListener('close', () => terminated()); - if (blocking) { - db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event)); - } - }) - .catch(() => { }); - return openPromise; - } - /** - * Delete a database. - * - * @param name Name of the database. - */ - function deleteDB(name, { blocked } = {}) { - const request = indexedDB.deleteDatabase(name); - if (blocked) { - request.addEventListener('blocked', (event) => blocked( - // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 - event.oldVersion, event)); - } - return wrap(request).then(() => undefined); - } - - const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; - const writeMethods = ['put', 'add', 'delete', 'clear']; - const cachedMethods = new Map(); - function getMethod(target, prop) { - if (!(target instanceof IDBDatabase && - !(prop in target) && - typeof prop === 'string')) { - return; - } - if (cachedMethods.get(prop)) - return cachedMethods.get(prop); - const targetFuncName = prop.replace(/FromIndex$/, ''); - const useIndex = prop !== targetFuncName; - const isWrite = writeMethods.includes(targetFuncName); - if ( - // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. - !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || - !(isWrite || readMethods.includes(targetFuncName))) { - return; - } - const method = async function (storeName, ...args) { - // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( - const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); - let target = tx.store; - if (useIndex) - target = target.index(args.shift()); - // Must reject if op rejects. - // If it's a write operation, must reject if tx.done rejects. - // Must reject with op rejection first. - // Must resolve with op value. - // Must handle both promises (no unhandled rejections) - return (await Promise.all([ - target[targetFuncName](...args), - isWrite && tx.done, - ]))[0]; - }; - cachedMethods.set(prop, method); - return method; - } - replaceTraps((oldTraps) => ({ - ...oldTraps, - get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), - has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop), - })); - - var build = /*#__PURE__*/Object.freeze({ - __proto__: null, - deleteDB: deleteDB, - openDB: openDB, - unwrap: unwrap, - wrap: wrap - }); - - var require$$3 = /*@__PURE__*/getAugmentedNamespace(build); - - (function (exports) { - - Object.defineProperty(exports, '__esModule', { value: true }); - - var component = index_cjs$1; - var logger$1 = index_cjs; - var util = require$$4; - var idb = require$$3; - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - class PlatformLoggerServiceImpl { - constructor(container) { - this.container = container; - } - // In initial implementation, this will be called by installations on - // auth token refresh, and installations will send this string. - getPlatformInfoString() { - const providers = this.container.getProviders(); - // Loop through providers and get library/version pairs from any that are - // version components. - return providers - .map(provider => { - if (isVersionServiceProvider(provider)) { - const service = provider.getImmediate(); - return `${service.library}/${service.version}`; - } - else { - return null; - } - }) - .filter(logString => logString) - .join(' '); - } - } - /** - * - * @param provider check if this provider provides a VersionService - * - * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider - * provides VersionService. The provider is not necessarily a 'app-version' - * provider. - */ - function isVersionServiceProvider(provider) { - const component = provider.getComponent(); - return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */; - } - - const name$q = "@firebase/app"; - const version$1 = "0.10.15"; - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - const logger = new logger$1.Logger('@firebase/app'); - - const name$p = "@firebase/app-compat"; - - const name$o = "@firebase/analytics-compat"; - - const name$n = "@firebase/analytics"; - - const name$m = "@firebase/app-check-compat"; - - const name$l = "@firebase/app-check"; - - const name$k = "@firebase/auth"; - - const name$j = "@firebase/auth-compat"; - - const name$i = "@firebase/database"; - - const name$h = "@firebase/data-connect"; - - const name$g = "@firebase/database-compat"; - - const name$f = "@firebase/functions"; - - const name$e = "@firebase/functions-compat"; - - const name$d = "@firebase/installations"; - - const name$c = "@firebase/installations-compat"; - - const name$b = "@firebase/messaging"; - - const name$a = "@firebase/messaging-compat"; - - const name$9 = "@firebase/performance"; - - const name$8 = "@firebase/performance-compat"; - - const name$7 = "@firebase/remote-config"; - - const name$6 = "@firebase/remote-config-compat"; - - const name$5 = "@firebase/storage"; - - const name$4 = "@firebase/storage-compat"; - - const name$3 = "@firebase/firestore"; - - const name$2 = "@firebase/vertexai"; - - const name$1 = "@firebase/firestore-compat"; - - const name = "firebase"; - const version = "11.0.1"; - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - /** - * The default app name - * - * @internal - */ - const DEFAULT_ENTRY_NAME = '[DEFAULT]'; - const PLATFORM_LOG_STRING = { - [name$q]: 'fire-core', - [name$p]: 'fire-core-compat', - [name$n]: 'fire-analytics', - [name$o]: 'fire-analytics-compat', - [name$l]: 'fire-app-check', - [name$m]: 'fire-app-check-compat', - [name$k]: 'fire-auth', - [name$j]: 'fire-auth-compat', - [name$i]: 'fire-rtdb', - [name$h]: 'fire-data-connect', - [name$g]: 'fire-rtdb-compat', - [name$f]: 'fire-fn', - [name$e]: 'fire-fn-compat', - [name$d]: 'fire-iid', - [name$c]: 'fire-iid-compat', - [name$b]: 'fire-fcm', - [name$a]: 'fire-fcm-compat', - [name$9]: 'fire-perf', - [name$8]: 'fire-perf-compat', - [name$7]: 'fire-rc', - [name$6]: 'fire-rc-compat', - [name$5]: 'fire-gcs', - [name$4]: 'fire-gcs-compat', - [name$3]: 'fire-fst', - [name$1]: 'fire-fst-compat', - [name$2]: 'fire-vertex', - 'fire-js': 'fire-js', - [name]: 'fire-js-all' - }; - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - /** - * @internal - */ - const _apps = new Map(); - /** - * @internal - */ - const _serverApps = new Map(); - /** - * Registered components. - * - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const _components = new Map(); - /** - * @param component - the component being added to this app's container - * - * @internal - */ - function _addComponent(app, component) { - try { - app.container.addComponent(component); - } - catch (e) { - logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e); - } - } - /** - * - * @internal - */ - function _addOrOverwriteComponent(app, component) { - app.container.addOrOverwriteComponent(component); - } - /** - * - * @param component - the component to register - * @returns whether or not the component is registered successfully - * - * @internal - */ - function _registerComponent(component) { - const componentName = component.name; - if (_components.has(componentName)) { - logger.debug(`There were multiple attempts to register component ${componentName}.`); - return false; - } - _components.set(componentName, component); - // add the component to existing app instances - for (const app of _apps.values()) { - _addComponent(app, component); - } - for (const serverApp of _serverApps.values()) { - _addComponent(serverApp, component); - } - return true; - } - /** - * - * @param app - FirebaseApp instance - * @param name - service name - * - * @returns the provider for the service with the matching name - * - * @internal - */ - function _getProvider(app, name) { - const heartbeatController = app.container - .getProvider('heartbeat') - .getImmediate({ optional: true }); - if (heartbeatController) { - void heartbeatController.triggerHeartbeat(); - } - return app.container.getProvider(name); - } - /** - * - * @param app - FirebaseApp instance - * @param name - service name - * @param instanceIdentifier - service instance identifier in case the service supports multiple instances - * - * @internal - */ - function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) { - _getProvider(app, name).clearInstance(instanceIdentifier); - } - /** - * - * @param obj - an object of type FirebaseApp or FirebaseOptions. - * - * @returns true if the provide object is of type FirebaseApp. - * - * @internal - */ - function _isFirebaseApp(obj) { - return obj.options !== undefined; - } - /** - * - * @param obj - an object of type FirebaseApp. - * - * @returns true if the provided object is of type FirebaseServerAppImpl. - * - * @internal - */ - function _isFirebaseServerApp(obj) { - return obj.settings !== undefined; - } - /** - * Test only - * - * @internal - */ - function _clearComponents() { - _components.clear(); - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - const ERRORS = { - ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " + - 'call initializeApp() first', - ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'", - ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config", - ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted", - ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted', - ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.', - ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' + - 'Firebase App instance.', - ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.', - ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.', - ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.', - ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.', - ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.', - ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.', - ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.' - }; - const ERROR_FACTORY = new util.ErrorFactory('app', 'Firebase', ERRORS); - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - class FirebaseAppImpl { - constructor(options, config, container) { - this._isDeleted = false; - this._options = Object.assign({}, options); - this._config = Object.assign({}, config); - this._name = config.name; - this._automaticDataCollectionEnabled = - config.automaticDataCollectionEnabled; - this._container = container; - this.container.addComponent(new component.Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */)); - } - get automaticDataCollectionEnabled() { - this.checkDestroyed(); - return this._automaticDataCollectionEnabled; - } - set automaticDataCollectionEnabled(val) { - this.checkDestroyed(); - this._automaticDataCollectionEnabled = val; - } - get name() { - this.checkDestroyed(); - return this._name; - } - get options() { - this.checkDestroyed(); - return this._options; - } - get config() { - this.checkDestroyed(); - return this._config; - } - get container() { - return this._container; - } - get isDeleted() { - return this._isDeleted; - } - set isDeleted(val) { - this._isDeleted = val; - } - /** - * This function will throw an Error if the App has already been deleted - - * use before performing API actions on the App. - */ - checkDestroyed() { - if (this.isDeleted) { - throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name }); - } - } - } - - /** - * @license - * Copyright 2023 Google LLC - * - * 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. - */ - class FirebaseServerAppImpl extends FirebaseAppImpl { - constructor(options, serverConfig, name, container) { - // Build configuration parameters for the FirebaseAppImpl base class. - const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined - ? serverConfig.automaticDataCollectionEnabled - : false; - // Create the FirebaseAppSettings object for the FirebaseAppImp constructor. - const config = { - name, - automaticDataCollectionEnabled - }; - if (options.apiKey !== undefined) { - // Construct the parent FirebaseAppImp object. - super(options, config, container); - } - else { - const appImpl = options; - super(appImpl.options, config, container); - } - // Now construct the data for the FirebaseServerAppImpl. - this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig); - this._finalizationRegistry = null; - if (typeof FinalizationRegistry !== 'undefined') { - this._finalizationRegistry = new FinalizationRegistry(() => { - this.automaticCleanup(); - }); - } - this._refCount = 0; - this.incRefCount(this._serverConfig.releaseOnDeref); - // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry - // will never trigger. - this._serverConfig.releaseOnDeref = undefined; - serverConfig.releaseOnDeref = undefined; - registerVersion(name$q, version$1, 'serverapp'); - } - toJSON() { - return undefined; - } - get refCount() { - return this._refCount; - } - // Increment the reference count of this server app. If an object is provided, register it - // with the finalization registry. - incRefCount(obj) { - if (this.isDeleted) { - return; - } - this._refCount++; - if (obj !== undefined && this._finalizationRegistry !== null) { - this._finalizationRegistry.register(obj, this); - } - } - // Decrement the reference count. - decRefCount() { - if (this.isDeleted) { - return 0; - } - return --this._refCount; - } - // Invoked by the FinalizationRegistry callback to note that this app should go through its - // reference counts and delete itself if no reference count remain. The coordinating logic that - // handles this is in deleteApp(...). - automaticCleanup() { - void deleteApp(this); - } - get settings() { - this.checkDestroyed(); - return this._serverConfig; - } - /** - * This function will throw an Error if the App has already been deleted - - * use before performing API actions on the App. - */ - checkDestroyed() { - if (this.isDeleted) { - throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */); - } - } - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - /** - * The current SDK version. - * - * @public - */ - const SDK_VERSION = version; - function initializeApp(_options, rawConfig = {}) { - let options = _options; - if (typeof rawConfig !== 'object') { - const name = rawConfig; - rawConfig = { name }; - } - const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig); - const name = config.name; - if (typeof name !== 'string' || !name) { - throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, { - appName: String(name) - }); - } - options || (options = util.getDefaultAppConfig()); - if (!options) { - throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */); - } - const existingApp = _apps.get(name); - if (existingApp) { - // return the existing app if options and config deep equal the ones in the existing app. - if (util.deepEqual(options, existingApp.options) && - util.deepEqual(config, existingApp.config)) { - return existingApp; - } - else { - throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name }); - } - } - const container = new component.ComponentContainer(name); - for (const component of _components.values()) { - container.addComponent(component); - } - const newApp = new FirebaseAppImpl(options, config, container); - _apps.set(name, newApp); - return newApp; - } - function initializeServerApp(_options, _serverAppConfig) { - if (util.isBrowser() && !util.isWebWorker()) { - // FirebaseServerApp isn't designed to be run in browsers. - throw ERROR_FACTORY.create("invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */); - } - if (_serverAppConfig.automaticDataCollectionEnabled === undefined) { - _serverAppConfig.automaticDataCollectionEnabled = false; - } - let appOptions; - if (_isFirebaseApp(_options)) { - appOptions = _options.options; - } - else { - appOptions = _options; - } - // Build an app name based on a hash of the configuration options. - const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions); - // However, Do not mangle the name based on releaseOnDeref, since it will vary between the - // construction of FirebaseServerApp instances. For example, if the object is the request headers. - if (nameObj.releaseOnDeref !== undefined) { - delete nameObj.releaseOnDeref; - } - const hashCode = (s) => { - return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0); - }; - if (_serverAppConfig.releaseOnDeref !== undefined) { - if (typeof FinalizationRegistry === 'undefined') { - throw ERROR_FACTORY.create("finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {}); - } - } - const nameString = '' + hashCode(JSON.stringify(nameObj)); - const existingApp = _serverApps.get(nameString); - if (existingApp) { - existingApp.incRefCount(_serverAppConfig.releaseOnDeref); - return existingApp; - } - const container = new component.ComponentContainer(nameString); - for (const component of _components.values()) { - container.addComponent(component); - } - const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container); - _serverApps.set(nameString, newApp); - return newApp; - } - /** - * Retrieves a {@link @firebase/app#FirebaseApp} instance. - * - * When called with no arguments, the default app is returned. When an app name - * is provided, the app corresponding to that name is returned. - * - * An exception is thrown if the app being retrieved has not yet been - * initialized. - * - * @example - * ```javascript - * // Return the default app - * const app = getApp(); - * ``` - * - * @example - * ```javascript - * // Return a named app - * const otherApp = getApp("otherApp"); - * ``` - * - * @param name - Optional name of the app to return. If no name is - * provided, the default is `"[DEFAULT]"`. - * - * @returns The app corresponding to the provided app name. - * If no app name is provided, the default app is returned. - * - * @public - */ - function getApp(name = DEFAULT_ENTRY_NAME) { - const app = _apps.get(name); - if (!app && name === DEFAULT_ENTRY_NAME && util.getDefaultAppConfig()) { - return initializeApp(); - } - if (!app) { - throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name }); - } - return app; - } - /** - * A (read-only) array of all initialized apps. - * @public - */ - function getApps() { - return Array.from(_apps.values()); - } - /** - * Renders this app unusable and frees the resources of all associated - * services. - * - * @example - * ```javascript - * deleteApp(app) - * .then(function() { - * console.log("App deleted successfully"); - * }) - * .catch(function(error) { - * console.log("Error deleting app:", error); - * }); - * ``` - * - * @public - */ - async function deleteApp(app) { - let cleanupProviders = false; - const name = app.name; - if (_apps.has(name)) { - cleanupProviders = true; - _apps.delete(name); - } - else if (_serverApps.has(name)) { - const firebaseServerApp = app; - if (firebaseServerApp.decRefCount() <= 0) { - _serverApps.delete(name); - cleanupProviders = true; - } - } - if (cleanupProviders) { - await Promise.all(app.container - .getProviders() - .map(provider => provider.delete())); - app.isDeleted = true; - } - } - /** - * Registers a library's name and version for platform logging purposes. - * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) - * @param version - Current version of that library. - * @param variant - Bundle variant, e.g., node, rn, etc. - * - * @public - */ - function registerVersion(libraryKeyOrName, version, variant) { - var _a; - // TODO: We can use this check to whitelist strings when/if we set up - // a good whitelist system. - let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName; - if (variant) { - library += `-${variant}`; - } - const libraryMismatch = library.match(/\s|\//); - const versionMismatch = version.match(/\s|\//); - if (libraryMismatch || versionMismatch) { - const warning = [ - `Unable to register library "${library}" with version "${version}":` - ]; - if (libraryMismatch) { - warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`); - } - if (libraryMismatch && versionMismatch) { - warning.push('and'); - } - if (versionMismatch) { - warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`); - } - logger.warn(warning.join(' ')); - return; - } - _registerComponent(new component.Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */)); - } - /** - * Sets log handler for all Firebase SDKs. - * @param logCallback - An optional custom log handler that executes user code whenever - * the Firebase SDK makes a logging call. - * - * @public - */ - function onLog(logCallback, options) { - if (logCallback !== null && typeof logCallback !== 'function') { - throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */); - } - logger$1.setUserLogHandler(logCallback, options); - } - /** - * Sets log level for all Firebase SDKs. - * - * All of the log types above the current log level are captured (i.e. if - * you set the log level to `info`, errors are logged, but `debug` and - * `verbose` logs are not). - * - * @public - */ - function setLogLevel(logLevel) { - logger$1.setLogLevel(logLevel); - } - - /** - * @license - * Copyright 2021 Google LLC - * - * 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. - */ - const DB_NAME = 'firebase-heartbeat-database'; - const DB_VERSION = 1; - const STORE_NAME = 'firebase-heartbeat-store'; - let dbPromise = null; - function getDbPromise() { - if (!dbPromise) { - dbPromise = idb.openDB(DB_NAME, DB_VERSION, { - upgrade: (db, oldVersion) => { - // We don't use 'break' in this switch statement, the fall-through - // behavior is what we want, because if there are multiple versions between - // the old version and the current version, we want ALL the migrations - // that correspond to those versions to run, not only the last one. - // eslint-disable-next-line default-case - switch (oldVersion) { - case 0: - try { - db.createObjectStore(STORE_NAME); - } - catch (e) { - // Safari/iOS browsers throw occasional exceptions on - // db.createObjectStore() that may be a bug. Avoid blocking - // the rest of the app functionality. - console.warn(e); - } - } - } - }).catch(e => { - throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, { - originalErrorMessage: e.message - }); - }); - } - return dbPromise; - } - async function readHeartbeatsFromIndexedDB(app) { - try { - const db = await getDbPromise(); - const tx = db.transaction(STORE_NAME); - const result = await tx.objectStore(STORE_NAME).get(computeKey(app)); - // We already have the value but tx.done can throw, - // so we need to await it here to catch errors - await tx.done; - return result; - } - catch (e) { - if (e instanceof util.FirebaseError) { - logger.warn(e.message); - } - else { - const idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, { - originalErrorMessage: e === null || e === void 0 ? void 0 : e.message - }); - logger.warn(idbGetError.message); - } - } - } - async function writeHeartbeatsToIndexedDB(app, heartbeatObject) { - try { - const db = await getDbPromise(); - const tx = db.transaction(STORE_NAME, 'readwrite'); - const objectStore = tx.objectStore(STORE_NAME); - await objectStore.put(heartbeatObject, computeKey(app)); - await tx.done; - } - catch (e) { - if (e instanceof util.FirebaseError) { - logger.warn(e.message); - } - else { - const idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, { - originalErrorMessage: e === null || e === void 0 ? void 0 : e.message - }); - logger.warn(idbGetError.message); - } - } - } - function computeKey(app) { - return `${app.name}!${app.options.appId}`; - } - - /** - * @license - * Copyright 2021 Google LLC - * - * 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. - */ - const MAX_HEADER_BYTES = 1024; - // 30 days - const STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000; - class HeartbeatServiceImpl { - constructor(container) { - this.container = container; - /** - * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate - * the header string. - * Stores one record per date. This will be consolidated into the standard - * format of one record per user agent string before being sent as a header. - * Populated from indexedDB when the controller is instantiated and should - * be kept in sync with indexedDB. - * Leave public for easier testing. - */ - this._heartbeatsCache = null; - const app = this.container.getProvider('app').getImmediate(); - this._storage = new HeartbeatStorageImpl(app); - this._heartbeatsCachePromise = this._storage.read().then(result => { - this._heartbeatsCache = result; - return result; - }); - } - /** - * Called to report a heartbeat. The function will generate - * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it - * to IndexedDB. - * Note that we only store one heartbeat per day. So if a heartbeat for today is - * already logged, subsequent calls to this function in the same day will be ignored. - */ - async triggerHeartbeat() { - var _a, _b; - try { - const platformLogger = this.container - .getProvider('platform-logger') - .getImmediate(); - // This is the "Firebase user agent" string from the platform logger - // service, not the browser user agent. - const agent = platformLogger.getPlatformInfoString(); - const date = getUTCDateString(); - if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) { - this._heartbeatsCache = await this._heartbeatsCachePromise; - // If we failed to construct a heartbeats cache, then return immediately. - if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) { - return; - } - } - // Do not store a heartbeat if one is already stored for this day - // or if a header has already been sent today. - if (this._heartbeatsCache.lastSentHeartbeatDate === date || - this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) { - return; - } - else { - // There is no entry for this date. Create one. - this._heartbeatsCache.heartbeats.push({ date, agent }); - } - // Remove entries older than 30 days. - this._heartbeatsCache.heartbeats = - this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => { - const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf(); - const now = Date.now(); - return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS; - }); - return this._storage.overwrite(this._heartbeatsCache); - } - catch (e) { - logger.warn(e); - } - } - /** - * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly. - * It also clears all heartbeats from memory as well as in IndexedDB. - * - * NOTE: Consuming product SDKs should not send the header if this method - * returns an empty string. - */ - async getHeartbeatsHeader() { - var _a; - try { - if (this._heartbeatsCache === null) { - await this._heartbeatsCachePromise; - } - // If it's still null or the array is empty, there is no data to send. - if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null || - this._heartbeatsCache.heartbeats.length === 0) { - return ''; - } - const date = getUTCDateString(); - // Extract as many heartbeats from the cache as will fit under the size limit. - const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats); - const headerString = util.base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })); - // Store last sent date to prevent another being logged/sent for the same day. - this._heartbeatsCache.lastSentHeartbeatDate = date; - if (unsentEntries.length > 0) { - // Store any unsent entries if they exist. - this._heartbeatsCache.heartbeats = unsentEntries; - // This seems more likely than emptying the array (below) to lead to some odd state - // since the cache isn't empty and this will be called again on the next request, - // and is probably safest if we await it. - await this._storage.overwrite(this._heartbeatsCache); - } - else { - this._heartbeatsCache.heartbeats = []; - // Do not wait for this, to reduce latency. - void this._storage.overwrite(this._heartbeatsCache); - } - return headerString; - } - catch (e) { - logger.warn(e); - return ''; - } - } - } - function getUTCDateString() { - const today = new Date(); - // Returns date format 'YYYY-MM-DD' - return today.toISOString().substring(0, 10); - } - function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) { - // Heartbeats grouped by user agent in the standard format to be sent in - // the header. - const heartbeatsToSend = []; - // Single date format heartbeats that are not sent. - let unsentEntries = heartbeatsCache.slice(); - for (const singleDateHeartbeat of heartbeatsCache) { - // Look for an existing entry with the same user agent. - const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent); - if (!heartbeatEntry) { - // If no entry for this user agent exists, create one. - heartbeatsToSend.push({ - agent: singleDateHeartbeat.agent, - dates: [singleDateHeartbeat.date] - }); - if (countBytes(heartbeatsToSend) > maxSize) { - // If the header would exceed max size, remove the added heartbeat - // entry and stop adding to the header. - heartbeatsToSend.pop(); - break; - } - } - else { - heartbeatEntry.dates.push(singleDateHeartbeat.date); - // If the header would exceed max size, remove the added date - // and stop adding to the header. - if (countBytes(heartbeatsToSend) > maxSize) { - heartbeatEntry.dates.pop(); - break; - } - } - // Pop unsent entry from queue. (Skipped if adding the entry exceeded - // quota and the loop breaks early.) - unsentEntries = unsentEntries.slice(1); - } - return { - heartbeatsToSend, - unsentEntries - }; - } - class HeartbeatStorageImpl { - constructor(app) { - this.app = app; - this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck(); - } - async runIndexedDBEnvironmentCheck() { - if (!util.isIndexedDBAvailable()) { - return false; - } - else { - return util.validateIndexedDBOpenable() - .then(() => true) - .catch(() => false); - } - } - /** - * Read all heartbeats. - */ - async read() { - const canUseIndexedDB = await this._canUseIndexedDBPromise; - if (!canUseIndexedDB) { - return { heartbeats: [] }; - } - else { - const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app); - if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) { - return idbHeartbeatObject; - } - else { - return { heartbeats: [] }; - } - } - } - // overwrite the storage with the provided heartbeats - async overwrite(heartbeatsObject) { - var _a; - const canUseIndexedDB = await this._canUseIndexedDBPromise; - if (!canUseIndexedDB) { - return; - } - else { - const existingHeartbeatsObject = await this.read(); - return writeHeartbeatsToIndexedDB(this.app, { - lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, - heartbeats: heartbeatsObject.heartbeats - }); - } - } - // add heartbeats - async add(heartbeatsObject) { - var _a; - const canUseIndexedDB = await this._canUseIndexedDBPromise; - if (!canUseIndexedDB) { - return; - } - else { - const existingHeartbeatsObject = await this.read(); - return writeHeartbeatsToIndexedDB(this.app, { - lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, - heartbeats: [ - ...existingHeartbeatsObject.heartbeats, - ...heartbeatsObject.heartbeats - ] - }); - } - } - } - /** - * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped - * in a platform logging header JSON object, stringified, and converted - * to base 64. - */ - function countBytes(heartbeatsCache) { - // base64 has a restricted set of characters, all of which should be 1 byte. - return util.base64urlEncodeWithoutPadding( - // heartbeatsCache wrapper properties - JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length; - } - - /** - * @license - * Copyright 2019 Google LLC - * - * 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. - */ - function registerCoreComponents(variant) { - _registerComponent(new component.Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */)); - _registerComponent(new component.Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */)); - // Register `app` package. - registerVersion(name$q, version$1, variant); - // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation - registerVersion(name$q, version$1, 'cjs2017'); - // Register platform SDK identifier (no version). - registerVersion('fire-js', ''); - } - - /** - * Firebase App - * - * @remarks This package coordinates the communication between the different Firebase components - * @packageDocumentation - */ - registerCoreComponents('node'); - - Object.defineProperty(exports, 'FirebaseError', { - enumerable: true, - get: function () { return util.FirebaseError; } - }); - exports.SDK_VERSION = SDK_VERSION; - exports._DEFAULT_ENTRY_NAME = DEFAULT_ENTRY_NAME; - exports._addComponent = _addComponent; - exports._addOrOverwriteComponent = _addOrOverwriteComponent; - exports._apps = _apps; - exports._clearComponents = _clearComponents; - exports._components = _components; - exports._getProvider = _getProvider; - exports._isFirebaseApp = _isFirebaseApp; - exports._isFirebaseServerApp = _isFirebaseServerApp; - exports._registerComponent = _registerComponent; - exports._removeServiceInstance = _removeServiceInstance; - exports._serverApps = _serverApps; - exports.deleteApp = deleteApp; - exports.getApp = getApp; - exports.getApps = getApps; - exports.initializeApp = initializeApp; - exports.initializeServerApp = initializeServerApp; - exports.onLog = onLog; - exports.registerVersion = registerVersion; - exports.setLogLevel = setLogLevel; - - } (index_cjs$2)); - - exports.browser$1 = browser$1$1; - exports.getAugmentedNamespace = getAugmentedNamespace; - exports.global = global$1; - exports.index_cjs = index_cjs$2; - exports.index_cjs$1 = index_cjs; - exports.index_cjs$2 = index_cjs$1; - exports.require$$4 = require$$4; - -})); diff --git a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.esm2017.js b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.esm2017.js new file mode 100644 index 00000000..3490fda6 --- /dev/null +++ b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.esm2017.js @@ -0,0 +1,2708 @@ +sap.ui.define(['exports'], (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version$2 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var browser$1 = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version$2, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + const stringToByteArray$1 = function (str) { + const out = []; + let p = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } else if (c < 2048) { + out[p++] = c >> 6 | 192; + out[p++] = c & 63 | 128; + } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) { + c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023); + out[p++] = c >> 18 | 240; + out[p++] = c >> 12 & 63 | 128; + out[p++] = c >> 6 & 63 | 128; + out[p++] = c & 63 | 128; + } else { + out[p++] = c >> 12 | 224; + out[p++] = c >> 6 & 63 | 128; + out[p++] = c & 63 | 128; + } + } + return out; + }; + const byteArrayToString = function (bytes) { + const out = []; + let pos = 0, c = 0; + while (pos < bytes.length) { + const c1 = bytes[pos++]; + if (c1 < 128) { + out[c++] = String.fromCharCode(c1); + } else if (c1 > 191 && c1 < 224) { + const c2 = bytes[pos++]; + out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); + } else if (c1 > 239 && c1 < 365) { + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + const c4 = bytes[pos++]; + const u = ((c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 65536; + out[c++] = String.fromCharCode(55296 + (u >> 10)); + out[c++] = String.fromCharCode(56320 + (u & 1023)); + } else { + const c2 = bytes[pos++]; + const c3 = bytes[pos++]; + out[c++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63); + } + } + return out.join(""); + }; + const base64 = { + byteToCharMap_: null, + charToByteMap_: null, + byteToCharMapWebSafe_: null, + charToByteMapWebSafe_: null, + ENCODED_VALS_BASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789", + get ENCODED_VALS() { + return this.ENCODED_VALS_BASE + "+/="; + }, + get ENCODED_VALS_WEBSAFE() { + return this.ENCODED_VALS_BASE + "-_."; + }, + HAS_NATIVE_SUPPORT: typeof atob === "function", + encodeByteArray(input, webSafe) { + if (!Array.isArray(input)) { + throw Error("encodeByteArray takes an array as a parameter"); + } + this.init_(); + const byteToCharMap = webSafe ? this.byteToCharMapWebSafe_ : this.byteToCharMap_; + const output = []; + for (let i = 0; i < input.length; i += 3) { + const byte1 = input[i]; + const haveByte2 = i + 1 < input.length; + const byte2 = haveByte2 ? input[i + 1] : 0; + const haveByte3 = i + 2 < input.length; + const byte3 = haveByte3 ? input[i + 2] : 0; + const outByte1 = byte1 >> 2; + const outByte2 = (byte1 & 3) << 4 | byte2 >> 4; + let outByte3 = (byte2 & 15) << 2 | byte3 >> 6; + let outByte4 = byte3 & 63; + if (!haveByte3) { + outByte4 = 64; + if (!haveByte2) { + outByte3 = 64; + } + } + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); + } + return output.join(""); + }, + encodeString(input, webSafe) { + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return btoa(input); + } + return this.encodeByteArray(stringToByteArray$1(input), webSafe); + }, + decodeString(input, webSafe) { + if (this.HAS_NATIVE_SUPPORT && !webSafe) { + return atob(input); + } + return byteArrayToString(this.decodeStringToByteArray(input, webSafe)); + }, + decodeStringToByteArray(input, webSafe) { + this.init_(); + const charToByteMap = webSafe ? this.charToByteMapWebSafe_ : this.charToByteMap_; + const output = []; + for (let i = 0; i < input.length; ) { + const byte1 = charToByteMap[input.charAt(i++)]; + const haveByte2 = i < input.length; + const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; + ++i; + const haveByte3 = i < input.length; + const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; + ++i; + const haveByte4 = i < input.length; + const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; + ++i; + if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { + throw new DecodeBase64StringError(); + } + const outByte1 = byte1 << 2 | byte2 >> 4; + output.push(outByte1); + if (byte3 !== 64) { + const outByte2 = byte2 << 4 & 240 | byte3 >> 2; + output.push(outByte2); + if (byte4 !== 64) { + const outByte3 = byte3 << 6 & 192 | byte4; + output.push(outByte3); + } + } + } + return output; + }, + init_() { + if (!this.byteToCharMap_) { + this.byteToCharMap_ = {}; + this.charToByteMap_ = {}; + this.byteToCharMapWebSafe_ = {}; + this.charToByteMapWebSafe_ = {}; + for (let i = 0; i < this.ENCODED_VALS.length; i++) { + this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); + this.charToByteMap_[this.byteToCharMap_[i]] = i; + this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); + this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; + if (i >= this.ENCODED_VALS_BASE.length) { + this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; + this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; + } + } + } + } + }; + class DecodeBase64StringError extends Error { + constructor() { + super(...arguments); + this.name = "DecodeBase64StringError"; + } + } + const base64Encode = function (str) { + const utf8Bytes = stringToByteArray$1(str); + return base64.encodeByteArray(utf8Bytes, true); + }; + const base64urlEncodeWithoutPadding = function (str) { + return base64Encode(str).replace(/\./g, ""); + }; + const base64Decode = function (str) { + try { + return base64.decodeString(str, true); + } catch (e) { + console.error("base64Decode failed: ", e); + } + return null; + }; + function getGlobal() { + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global$1 !== "undefined") { + return global$1; + } + throw new Error("Unable to locate global object."); + } + const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; + const getDefaultsFromEnvVariable = () => { + if (typeof browser$1 === "undefined" || typeof browser$1.env === "undefined") { + return; + } + const defaultsJsonString = browser$1.env.__FIREBASE_DEFAULTS__; + if (defaultsJsonString) { + return JSON.parse(defaultsJsonString); + } + }; + const getDefaultsFromCookie = () => { + if (typeof document === "undefined") { + return; + } + let match; + try { + match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/); + } catch (e) { + return; + } + const decoded = match && base64Decode(match[1]); + return decoded && JSON.parse(decoded); + }; + const getDefaults = () => { + try { + return getDefaultsFromGlobal() || getDefaultsFromEnvVariable() || getDefaultsFromCookie(); + } catch (e) { + console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`); + return; + } + }; + const getDefaultEmulatorHost = productName => { + var _a, _b; + return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; + }; + const getDefaultEmulatorHostnameAndPort = productName => { + const host = getDefaultEmulatorHost(productName); + if (!host) { + return undefined; + } + const separatorIndex = host.lastIndexOf(":"); + if (separatorIndex <= 0 || separatorIndex + 1 === host.length) { + throw new Error(`Invalid host ${host} with no separate hostname and port!`); + } + const port = parseInt(host.substring(separatorIndex + 1), 10); + if (host[0] === "[") { + return [host.substring(1, separatorIndex - 1), port]; + } else { + return [host.substring(0, separatorIndex), port]; + } + }; + const getDefaultAppConfig = () => { + var _a; + return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; + }; + class Deferred { + constructor() { + this.reject = () => {}; + this.resolve = () => {}; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + wrapCallback(callback) { + return (error, value) => { + if (error) { + this.reject(error); + } else { + this.resolve(value); + } + if (typeof callback === "function") { + this.promise.catch(() => {}); + if (callback.length === 1) { + callback(error); + } else { + callback(error, value); + } + } + }; + } + } + function createMockUserToken(token, projectId) { + if (token.uid) { + throw new Error("The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID."); + } + const header = { + alg: "none", + type: "JWT" + }; + const project = projectId || "demo-project"; + const iat = token.iat || 0; + const sub = token.sub || token.user_id; + if (!sub) { + throw new Error("mockUserToken must contain 'sub' or 'user_id' field!"); + } + const payload = Object.assign({ + iss: `https://securetoken.google.com/${project}`, + aud: project, + iat, + exp: iat + 3600, + auth_time: iat, + sub, + user_id: sub, + firebase: { + sign_in_provider: "custom", + identities: {} + } + }, token); + const signature = ""; + return [base64urlEncodeWithoutPadding(JSON.stringify(header)), base64urlEncodeWithoutPadding(JSON.stringify(payload)), signature].join("."); + } + function isBrowser() { + return typeof window !== "undefined" || isWebWorker(); + } + function isWebWorker() { + return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope; + } + function isIndexedDBAvailable() { + try { + return typeof indexedDB === "object"; + } catch (e) { + return false; + } + } + function validateIndexedDBOpenable() { + return new Promise((resolve, reject) => { + try { + let preExist = true; + const DB_CHECK_NAME = "validate-browser-context-for-indexeddb-analytics-module"; + const request = self.indexedDB.open(DB_CHECK_NAME); + request.onsuccess = () => { + request.result.close(); + if (!preExist) { + self.indexedDB.deleteDatabase(DB_CHECK_NAME); + } + resolve(true); + }; + request.onupgradeneeded = () => { + preExist = false; + }; + request.onerror = () => { + var _a; + reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || ""); + }; + } catch (error) { + reject(error); + } + }); + } + const ERROR_NAME = "FirebaseError"; + class FirebaseError extends Error { + constructor(code, message, customData) { + super(message); + this.code = code; + this.customData = customData; + this.name = ERROR_NAME; + Object.setPrototypeOf(this, FirebaseError.prototype); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ErrorFactory.prototype.create); + } + } + } + class ErrorFactory { + constructor(service, serviceName, errors) { + this.service = service; + this.serviceName = serviceName; + this.errors = errors; + } + create(code, ...data) { + const customData = data[0] || ({}); + const fullCode = `${this.service}/${code}`; + const template = this.errors[code]; + const message = template ? replaceTemplate(template, customData) : "Error"; + const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; + const error = new FirebaseError(fullCode, fullMessage, customData); + return error; + } + } + function replaceTemplate(template, data) { + return template.replace(PATTERN, (_, key) => { + const value = data[key]; + return value != null ? String(value) : `<${key}?>`; + }); + } + const PATTERN = /\{\$([^}]+)}/g; + function deepEqual(a, b) { + if (a === b) { + return true; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + for (const k of aKeys) { + if (!bKeys.includes(k)) { + return false; + } + const aProp = a[k]; + const bProp = b[k]; + if (isObject(aProp) && isObject(bProp)) { + if (!deepEqual(aProp, bProp)) { + return false; + } + } else if (aProp !== bProp) { + return false; + } + } + for (const k of bKeys) { + if (!aKeys.includes(k)) { + return false; + } + } + return true; + } + function isObject(thing) { + return thing !== null && typeof thing === "object"; + } + function getModularInstance(service) { + if (service && service._delegate) { + return service._delegate; + } else { + return service; + } + } + + /** + * Component for service name T, e.g. `auth`, `auth-internal` + */ + class Component { + /** + * + * @param name The public service name, e.g. app, auth, firestore, database + * @param instanceFactory Service factory responsible for creating the public interface + * @param type whether the service provided by the component is public or private + */ + constructor(name, instanceFactory, type) { + this.name = name; + this.instanceFactory = instanceFactory; + this.type = type; + this.multipleInstances = false; + /** + * Properties to be added to the service namespace + */ + this.serviceProps = {}; + this.instantiationMode = "LAZY" /* InstantiationMode.LAZY */; + this.onInstanceCreated = null; + } + setInstantiationMode(mode) { + this.instantiationMode = mode; + return this; + } + setMultipleInstances(multipleInstances) { + this.multipleInstances = multipleInstances; + return this; + } + setServiceProps(props) { + this.serviceProps = props; + return this; + } + setInstanceCreatedCallback(callback) { + this.onInstanceCreated = callback; + return this; + } + } + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + const DEFAULT_ENTRY_NAME$1 = '[DEFAULT]'; + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + /** + * Provider for instance for service name T, e.g. 'auth', 'auth-internal' + * NameServiceMapping[T] is an alias for the type of the instance + */ + class Provider { + constructor(name, container) { + this.name = name; + this.container = container; + this.component = null; + this.instances = new Map(); + this.instancesDeferred = new Map(); + this.instancesOptions = new Map(); + this.onInitCallbacks = new Map(); + } + /** + * @param identifier A provider can provide multiple instances of a service + * if this.component.multipleInstances is true. + */ + get(identifier) { + // if multipleInstances is not supported, use the default name + const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + if (!this.instancesDeferred.has(normalizedIdentifier)) { + const deferred = new Deferred(); + this.instancesDeferred.set(normalizedIdentifier, deferred); + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + // initialize the service if it can be auto-initialized + try { + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + if (instance) { + deferred.resolve(instance); + } + } + catch (e) { + // when the instance factory throws an exception during get(), it should not cause + // a fatal error. We just return the unresolved promise in this case. + } + } + } + return this.instancesDeferred.get(normalizedIdentifier).promise; + } + getImmediate(options) { + var _a; + // if multipleInstances is not supported, use the default name + const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); + const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false; + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + try { + return this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + } + catch (e) { + if (optional) { + return null; + } + else { + throw e; + } + } + } + else { + // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw + if (optional) { + return null; + } + else { + throw Error(`Service ${this.name} is not available`); + } + } + } + getComponent() { + return this.component; + } + setComponent(component) { + if (component.name !== this.name) { + throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`); + } + if (this.component) { + throw Error(`Component for ${this.name} has already been provided`); + } + this.component = component; + // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) + if (!this.shouldAutoInitialize()) { + return; + } + // if the service is eager, initialize the default instance + if (isComponentEager(component)) { + try { + this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME$1 }); + } + catch (e) { + // when the instance factory for an eager Component throws an exception during the eager + // initialization, it should not cause a fatal error. + // TODO: Investigate if we need to make it configurable, because some component may want to cause + // a fatal error in this case? + } + } + // Create service instances for the pending promises and resolve them + // NOTE: if this.multipleInstances is false, only the default instance will be created + // and all promises with resolve with it regardless of the identifier. + for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { + const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + try { + // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier + }); + instanceDeferred.resolve(instance); + } + catch (e) { + // when the instance factory throws an exception, it should not cause + // a fatal error. We just leave the promise unresolved. + } + } + } + clearInstance(identifier = DEFAULT_ENTRY_NAME$1) { + this.instancesDeferred.delete(identifier); + this.instancesOptions.delete(identifier); + this.instances.delete(identifier); + } + // app.delete() will call this method on every provider to delete the services + // TODO: should we mark the provider as deleted? + async delete() { + const services = Array.from(this.instances.values()); + await Promise.all([ + ...services + .filter(service => 'INTERNAL' in service) // legacy services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(service => service.INTERNAL.delete()), + ...services + .filter(service => '_delete' in service) // modularized services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(service => service._delete()) + ]); + } + isComponentSet() { + return this.component != null; + } + isInitialized(identifier = DEFAULT_ENTRY_NAME$1) { + return this.instances.has(identifier); + } + getOptions(identifier = DEFAULT_ENTRY_NAME$1) { + return this.instancesOptions.get(identifier) || {}; + } + initialize(opts = {}) { + const { options = {} } = opts; + const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); + if (this.isInitialized(normalizedIdentifier)) { + throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`); + } + if (!this.isComponentSet()) { + throw Error(`Component ${this.name} has not been registered yet`); + } + const instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier, + options + }); + // resolve any pending promise waiting for the service instance + for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { + const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + if (normalizedIdentifier === normalizedDeferredIdentifier) { + instanceDeferred.resolve(instance); + } + } + return instance; + } + /** + * + * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). + * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. + * + * @param identifier An optional instance identifier + * @returns a function to unregister the callback + */ + onInit(callback, identifier) { + var _a; + const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); + existingCallbacks.add(callback); + this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); + const existingInstance = this.instances.get(normalizedIdentifier); + if (existingInstance) { + callback(existingInstance, normalizedIdentifier); + } + return () => { + existingCallbacks.delete(callback); + }; + } + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + invokeOnInitCallbacks(instance, identifier) { + const callbacks = this.onInitCallbacks.get(identifier); + if (!callbacks) { + return; + } + for (const callback of callbacks) { + try { + callback(instance, identifier); + } + catch (_a) { + // ignore errors in the onInit callback + } + } + } + getOrInitializeService({ instanceIdentifier, options = {} }) { + let instance = this.instances.get(instanceIdentifier); + if (!instance && this.component) { + instance = this.component.instanceFactory(this.container, { + instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), + options + }); + this.instances.set(instanceIdentifier, instance); + this.instancesOptions.set(instanceIdentifier, options); + /** + * Invoke onInit listeners. + * Note this.component.onInstanceCreated is different, which is used by the component creator, + * while onInit listeners are registered by consumers of the provider. + */ + this.invokeOnInitCallbacks(instance, instanceIdentifier); + /** + * Order is important + * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which + * makes `isInitialized()` return true. + */ + if (this.component.onInstanceCreated) { + try { + this.component.onInstanceCreated(this.container, instanceIdentifier, instance); + } + catch (_a) { + // ignore errors in the onInstanceCreatedCallback + } + } + } + return instance || null; + } + normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME$1) { + if (this.component) { + return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME$1; + } + else { + return identifier; // assume multiple instances are supported before the component is provided. + } + } + shouldAutoInitialize() { + return (!!this.component && + this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */); + } + } + // undefined should be passed to the service factory for the default instance + function normalizeIdentifierForFactory(identifier) { + return identifier === DEFAULT_ENTRY_NAME$1 ? undefined : identifier; + } + function isComponentEager(component) { + return component.instantiationMode === "EAGER" /* InstantiationMode.EAGER */; + } + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + /** + * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` + */ + class ComponentContainer { + constructor(name) { + this.name = name; + this.providers = new Map(); + } + /** + * + * @param component Component being added + * @param overwrite When a component with the same name has already been registered, + * if overwrite is true: overwrite the existing component with the new component and create a new + * provider with the new component. It can be useful in tests where you want to use different mocks + * for different tests. + * if overwrite is false: throw an exception + */ + addComponent(component) { + const provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + throw new Error(`Component ${component.name} has already been registered with ${this.name}`); + } + provider.setComponent(component); + } + addOrOverwriteComponent(component) { + const provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + // delete the existing provider from the container, so we can register the new component + this.providers.delete(component.name); + } + this.addComponent(component); + } + /** + * getProvider provides a type safe interface where it can only be called with a field name + * present in NameServiceMapping interface. + * + * Firebase SDKs providing services should extend NameServiceMapping interface to register + * themselves. + */ + getProvider(name) { + if (this.providers.has(name)) { + return this.providers.get(name); + } + // create a Provider for a service that hasn't registered with Firebase + const provider = new Provider(name, this); + this.providers.set(name, provider); + return provider; + } + getProviders() { + return Array.from(this.providers.values()); + } + } + + var index_cjs = {}; + + (function (exports) { + + Object.defineProperty(exports, '__esModule', { value: true }); + + /** + * @license + * Copyright 2017 Google LLC + * + * 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. + */ + /** + * A container for all of the Logger instances + */ + const instances = []; + /** + * The JS SDK supports 5 log levels and also allows a user the ability to + * silence the logs altogether. + * + * The order is a follows: + * DEBUG < VERBOSE < INFO < WARN < ERROR + * + * All of the log types above the current log level will be captured (i.e. if + * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and + * `VERBOSE` logs will not) + */ + exports.LogLevel = void 0; + (function (LogLevel) { + LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; + LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; + LogLevel[LogLevel["INFO"] = 2] = "INFO"; + LogLevel[LogLevel["WARN"] = 3] = "WARN"; + LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; + LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; + })(exports.LogLevel || (exports.LogLevel = {})); + const levelStringToEnum = { + 'debug': exports.LogLevel.DEBUG, + 'verbose': exports.LogLevel.VERBOSE, + 'info': exports.LogLevel.INFO, + 'warn': exports.LogLevel.WARN, + 'error': exports.LogLevel.ERROR, + 'silent': exports.LogLevel.SILENT + }; + /** + * The default log level + */ + const defaultLogLevel = exports.LogLevel.INFO; + /** + * By default, `console.debug` is not displayed in the developer console (in + * chrome). To avoid forcing users to have to opt-in to these logs twice + * (i.e. once for firebase, and once in the console), we are sending `DEBUG` + * logs to the `console.log` function. + */ + const ConsoleMethod = { + [exports.LogLevel.DEBUG]: 'log', + [exports.LogLevel.VERBOSE]: 'log', + [exports.LogLevel.INFO]: 'info', + [exports.LogLevel.WARN]: 'warn', + [exports.LogLevel.ERROR]: 'error' + }; + /** + * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR + * messages on to their corresponding console counterparts (if the log method + * is supported by the current log level) + */ + const defaultLogHandler = (instance, logType, ...args) => { + if (logType < instance.logLevel) { + return; + } + const now = new Date().toISOString(); + const method = ConsoleMethod[logType]; + if (method) { + console[method](`[${now}] ${instance.name}:`, ...args); + } + else { + throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`); + } + }; + class Logger { + /** + * Gives you an instance of a Logger to capture messages according to + * Firebase's logging scheme. + * + * @param name The name that the logs will be associated with + */ + constructor(name) { + this.name = name; + /** + * The log level of the given Logger instance. + */ + this._logLevel = defaultLogLevel; + /** + * The main (internal) log handler for the Logger instance. + * Can be set to a new function in internal package code but not by user. + */ + this._logHandler = defaultLogHandler; + /** + * The optional, additional, user-defined log handler for the Logger instance. + */ + this._userLogHandler = null; + /** + * Capture the current instance for later use + */ + instances.push(this); + } + get logLevel() { + return this._logLevel; + } + set logLevel(val) { + if (!(val in exports.LogLevel)) { + throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``); + } + this._logLevel = val; + } + // Workaround for setter/getter having to be the same type. + setLogLevel(val) { + this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; + } + get logHandler() { + return this._logHandler; + } + set logHandler(val) { + if (typeof val !== 'function') { + throw new TypeError('Value assigned to `logHandler` must be a function'); + } + this._logHandler = val; + } + get userLogHandler() { + return this._userLogHandler; + } + set userLogHandler(val) { + this._userLogHandler = val; + } + /** + * The functions below are all based on the `console` interface + */ + debug(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.DEBUG, ...args); + this._logHandler(this, exports.LogLevel.DEBUG, ...args); + } + log(...args) { + this._userLogHandler && + this._userLogHandler(this, exports.LogLevel.VERBOSE, ...args); + this._logHandler(this, exports.LogLevel.VERBOSE, ...args); + } + info(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.INFO, ...args); + this._logHandler(this, exports.LogLevel.INFO, ...args); + } + warn(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.WARN, ...args); + this._logHandler(this, exports.LogLevel.WARN, ...args); + } + error(...args) { + this._userLogHandler && this._userLogHandler(this, exports.LogLevel.ERROR, ...args); + this._logHandler(this, exports.LogLevel.ERROR, ...args); + } + } + function setLogLevel(level) { + instances.forEach(inst => { + inst.setLogLevel(level); + }); + } + function setUserLogHandler(logCallback, options) { + for (const instance of instances) { + let customLogLevel = null; + if (options && options.level) { + customLogLevel = levelStringToEnum[options.level]; + } + if (logCallback === null) { + instance.userLogHandler = null; + } + else { + instance.userLogHandler = (instance, level, ...args) => { + const message = args + .map(arg => { + if (arg == null) { + return null; + } + else if (typeof arg === 'string') { + return arg; + } + else if (typeof arg === 'number' || typeof arg === 'boolean') { + return arg.toString(); + } + else if (arg instanceof Error) { + return arg.message; + } + else { + try { + return JSON.stringify(arg); + } + catch (ignored) { + return null; + } + } + }) + .filter(arg => arg) + .join(' '); + if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) { + logCallback({ + level: exports.LogLevel[level].toLowerCase(), + message, + args, + type: instance.name + }); + } + }; + } + } + } + + exports.Logger = Logger; + exports.setLogLevel = setLogLevel; + exports.setUserLogHandler = setUserLogHandler; + + } (index_cjs)); + + const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); + + let idbProxyableTypes; + let cursorAdvanceMethods; + // This is a function to prevent it throwing up in node environments. + function getIdbProxyableTypes() { + return (idbProxyableTypes || + (idbProxyableTypes = [ + IDBDatabase, + IDBObjectStore, + IDBIndex, + IDBCursor, + IDBTransaction, + ])); + } + // This is a function to prevent it throwing up in node environments. + function getCursorAdvanceMethods() { + return (cursorAdvanceMethods || + (cursorAdvanceMethods = [ + IDBCursor.prototype.advance, + IDBCursor.prototype.continue, + IDBCursor.prototype.continuePrimaryKey, + ])); + } + const cursorRequestMap = new WeakMap(); + const transactionDoneMap = new WeakMap(); + const transactionStoreNamesMap = new WeakMap(); + const transformCache = new WeakMap(); + const reverseTransformCache = new WeakMap(); + function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener('success', success); + request.removeEventListener('error', error); + }; + const success = () => { + resolve(wrap(request.result)); + unlisten(); + }; + const error = () => { + reject(request.error); + unlisten(); + }; + request.addEventListener('success', success); + request.addEventListener('error', error); + }); + promise + .then((value) => { + // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval + // (see wrapFunction). + if (value instanceof IDBCursor) { + cursorRequestMap.set(value, request); + } + // Catching to avoid "Uncaught Promise exceptions" + }) + .catch(() => { }); + // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This + // is because we create many promises from a single IDBRequest. + reverseTransformCache.set(promise, request); + return promise; + } + function cacheDonePromiseForTransaction(tx) { + // Early bail if we've already created a done promise for this transaction. + if (transactionDoneMap.has(tx)) + return; + const done = new Promise((resolve, reject) => { + const unlisten = () => { + tx.removeEventListener('complete', complete); + tx.removeEventListener('error', error); + tx.removeEventListener('abort', error); + }; + const complete = () => { + resolve(); + unlisten(); + }; + const error = () => { + reject(tx.error || new DOMException('AbortError', 'AbortError')); + unlisten(); + }; + tx.addEventListener('complete', complete); + tx.addEventListener('error', error); + tx.addEventListener('abort', error); + }); + // Cache it for later retrieval. + transactionDoneMap.set(tx, done); + } + let idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + // Special handling for transaction.done. + if (prop === 'done') + return transactionDoneMap.get(target); + // Polyfill for objectStoreNames because of Edge. + if (prop === 'objectStoreNames') { + return target.objectStoreNames || transactionStoreNamesMap.get(target); + } + // Make tx.store return the only store in the transaction, or undefined if there are many. + if (prop === 'store') { + return receiver.objectStoreNames[1] + ? undefined + : receiver.objectStore(receiver.objectStoreNames[0]); + } + } + // Else transform whatever we get back. + return wrap(target[prop]); + }, + set(target, prop, value) { + target[prop] = value; + return true; + }, + has(target, prop) { + if (target instanceof IDBTransaction && + (prop === 'done' || prop === 'store')) { + return true; + } + return prop in target; + }, + }; + function replaceTraps(callback) { + idbProxyTraps = callback(idbProxyTraps); + } + function wrapFunction(func) { + // Due to expected object equality (which is enforced by the caching in `wrap`), we + // only create one new func per func. + // Edge doesn't support objectStoreNames (booo), so we polyfill it here. + if (func === IDBDatabase.prototype.transaction && + !('objectStoreNames' in IDBTransaction.prototype)) { + return function (storeNames, ...args) { + const tx = func.call(unwrap(this), storeNames, ...args); + transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); + return wrap(tx); + }; + } + // Cursor methods are special, as the behaviour is a little more different to standard IDB. In + // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the + // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense + // with real promises, so each advance methods returns a new promise for the cursor object, or + // undefined if the end of the cursor has been reached. + if (getCursorAdvanceMethods().includes(func)) { + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + func.apply(unwrap(this), args); + return wrap(cursorRequestMap.get(this)); + }; + } + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + return wrap(func.apply(unwrap(this), args)); + }; + } + function transformCachableValue(value) { + if (typeof value === 'function') + return wrapFunction(value); + // This doesn't return, it just creates a 'done' promise for the transaction, + // which is later returned for transaction.done (see idbObjectHandler). + if (value instanceof IDBTransaction) + cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) + return new Proxy(value, idbProxyTraps); + // Return the same value back if we're not going to transform it. + return value; + } + function wrap(value) { + // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because + // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. + if (value instanceof IDBRequest) + return promisifyRequest(value); + // If we've already transformed this value before, reuse the transformed value. + // This is faster, but it also provides object equality. + if (transformCache.has(value)) + return transformCache.get(value); + const newValue = transformCachableValue(value); + // Not all types are transformed. + // These may be primitive types, so they can't be WeakMap keys. + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + return newValue; + } + const unwrap = (value) => reverseTransformCache.get(value); + + /** + * Open a database. + * + * @param name Name of the database. + * @param version Schema version. + * @param callbacks Additional callbacks. + */ + function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { + const request = indexedDB.open(name, version); + const openPromise = wrap(request); + if (upgrade) { + request.addEventListener('upgradeneeded', (event) => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); + }); + } + if (blocked) { + request.addEventListener('blocked', (event) => blocked( + // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 + event.oldVersion, event.newVersion, event)); + } + openPromise + .then((db) => { + if (terminated) + db.addEventListener('close', () => terminated()); + if (blocking) { + db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event)); + } + }) + .catch(() => { }); + return openPromise; + } + + const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; + const writeMethods = ['put', 'add', 'delete', 'clear']; + const cachedMethods = new Map(); + function getMethod(target, prop) { + if (!(target instanceof IDBDatabase && + !(prop in target) && + typeof prop === 'string')) { + return; + } + if (cachedMethods.get(prop)) + return cachedMethods.get(prop); + const targetFuncName = prop.replace(/FromIndex$/, ''); + const useIndex = prop !== targetFuncName; + const isWrite = writeMethods.includes(targetFuncName); + if ( + // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. + !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || + !(isWrite || readMethods.includes(targetFuncName))) { + return; + } + const method = async function (storeName, ...args) { + // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( + const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); + let target = tx.store; + if (useIndex) + target = target.index(args.shift()); + // Must reject if op rejects. + // If it's a write operation, must reject if tx.done rejects. + // Must reject with op rejection first. + // Must resolve with op value. + // Must handle both promises (no unhandled rejections) + return (await Promise.all([ + target[targetFuncName](...args), + isWrite && tx.done, + ]))[0]; + }; + cachedMethods.set(prop, method); + return method; + } + replaceTraps((oldTraps) => ({ + ...oldTraps, + get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), + has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop), + })); + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + class PlatformLoggerServiceImpl { + constructor(container) { + this.container = container; + } + // In initial implementation, this will be called by installations on + // auth token refresh, and installations will send this string. + getPlatformInfoString() { + const providers = this.container.getProviders(); + // Loop through providers and get library/version pairs from any that are + // version components. + return providers + .map(provider => { + if (isVersionServiceProvider(provider)) { + const service = provider.getImmediate(); + return `${service.library}/${service.version}`; + } + else { + return null; + } + }) + .filter(logString => logString) + .join(' '); + } + } + /** + * + * @param provider check if this provider provides a VersionService + * + * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider + * provides VersionService. The provider is not necessarily a 'app-version' + * provider. + */ + function isVersionServiceProvider(provider) { + const component = provider.getComponent(); + return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */; + } + + const name$q = "@firebase/app"; + const version$1 = "0.10.15"; + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + const logger = new index_cjs.Logger('@firebase/app'); + + const name$p = "@firebase/app-compat"; + + const name$o = "@firebase/analytics-compat"; + + const name$n = "@firebase/analytics"; + + const name$m = "@firebase/app-check-compat"; + + const name$l = "@firebase/app-check"; + + const name$k = "@firebase/auth"; + + const name$j = "@firebase/auth-compat"; + + const name$i = "@firebase/database"; + + const name$h = "@firebase/data-connect"; + + const name$g = "@firebase/database-compat"; + + const name$f = "@firebase/functions"; + + const name$e = "@firebase/functions-compat"; + + const name$d = "@firebase/installations"; + + const name$c = "@firebase/installations-compat"; + + const name$b = "@firebase/messaging"; + + const name$a = "@firebase/messaging-compat"; + + const name$9 = "@firebase/performance"; + + const name$8 = "@firebase/performance-compat"; + + const name$7 = "@firebase/remote-config"; + + const name$6 = "@firebase/remote-config-compat"; + + const name$5 = "@firebase/storage"; + + const name$4 = "@firebase/storage-compat"; + + const name$3 = "@firebase/firestore"; + + const name$2 = "@firebase/vertexai"; + + const name$1 = "@firebase/firestore-compat"; + + const name = "firebase"; + const version = "11.0.1"; + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + /** + * The default app name + * + * @internal + */ + const DEFAULT_ENTRY_NAME = '[DEFAULT]'; + const PLATFORM_LOG_STRING = { + [name$q]: 'fire-core', + [name$p]: 'fire-core-compat', + [name$n]: 'fire-analytics', + [name$o]: 'fire-analytics-compat', + [name$l]: 'fire-app-check', + [name$m]: 'fire-app-check-compat', + [name$k]: 'fire-auth', + [name$j]: 'fire-auth-compat', + [name$i]: 'fire-rtdb', + [name$h]: 'fire-data-connect', + [name$g]: 'fire-rtdb-compat', + [name$f]: 'fire-fn', + [name$e]: 'fire-fn-compat', + [name$d]: 'fire-iid', + [name$c]: 'fire-iid-compat', + [name$b]: 'fire-fcm', + [name$a]: 'fire-fcm-compat', + [name$9]: 'fire-perf', + [name$8]: 'fire-perf-compat', + [name$7]: 'fire-rc', + [name$6]: 'fire-rc-compat', + [name$5]: 'fire-gcs', + [name$4]: 'fire-gcs-compat', + [name$3]: 'fire-fst', + [name$1]: 'fire-fst-compat', + [name$2]: 'fire-vertex', + 'fire-js': 'fire-js', + [name]: 'fire-js-all' + }; + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + /** + * @internal + */ + const _apps = new Map(); + /** + * @internal + */ + const _serverApps = new Map(); + /** + * Registered components. + * + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _components = new Map(); + /** + * @param component - the component being added to this app's container + * + * @internal + */ + function _addComponent(app, component) { + try { + app.container.addComponent(component); + } + catch (e) { + logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e); + } + } + /** + * + * @internal + */ + function _addOrOverwriteComponent(app, component) { + app.container.addOrOverwriteComponent(component); + } + /** + * + * @param component - the component to register + * @returns whether or not the component is registered successfully + * + * @internal + */ + function _registerComponent(component) { + const componentName = component.name; + if (_components.has(componentName)) { + logger.debug(`There were multiple attempts to register component ${componentName}.`); + return false; + } + _components.set(componentName, component); + // add the component to existing app instances + for (const app of _apps.values()) { + _addComponent(app, component); + } + for (const serverApp of _serverApps.values()) { + _addComponent(serverApp, component); + } + return true; + } + /** + * + * @param app - FirebaseApp instance + * @param name - service name + * + * @returns the provider for the service with the matching name + * + * @internal + */ + function _getProvider(app, name) { + const heartbeatController = app.container + .getProvider('heartbeat') + .getImmediate({ optional: true }); + if (heartbeatController) { + void heartbeatController.triggerHeartbeat(); + } + return app.container.getProvider(name); + } + /** + * + * @param app - FirebaseApp instance + * @param name - service name + * @param instanceIdentifier - service instance identifier in case the service supports multiple instances + * + * @internal + */ + function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) { + _getProvider(app, name).clearInstance(instanceIdentifier); + } + /** + * + * @param obj - an object of type FirebaseApp or FirebaseOptions. + * + * @returns true if the provide object is of type FirebaseApp. + * + * @internal + */ + function _isFirebaseApp(obj) { + return obj.options !== undefined; + } + /** + * + * @param obj - an object of type FirebaseApp. + * + * @returns true if the provided object is of type FirebaseServerAppImpl. + * + * @internal + */ + function _isFirebaseServerApp(obj) { + return obj.settings !== undefined; + } + /** + * Test only + * + * @internal + */ + function _clearComponents() { + _components.clear(); + } + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + const ERRORS = { + ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " + + 'call initializeApp() first', + ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'", + ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config", + ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted", + ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted', + ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.', + ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' + + 'Firebase App instance.', + ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.', + ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.', + ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.', + ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.', + ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.', + ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.', + ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.' + }; + const ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS); + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + class FirebaseAppImpl { + constructor(options, config, container) { + this._isDeleted = false; + this._options = Object.assign({}, options); + this._config = Object.assign({}, config); + this._name = config.name; + this._automaticDataCollectionEnabled = + config.automaticDataCollectionEnabled; + this._container = container; + this.container.addComponent(new Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */)); + } + get automaticDataCollectionEnabled() { + this.checkDestroyed(); + return this._automaticDataCollectionEnabled; + } + set automaticDataCollectionEnabled(val) { + this.checkDestroyed(); + this._automaticDataCollectionEnabled = val; + } + get name() { + this.checkDestroyed(); + return this._name; + } + get options() { + this.checkDestroyed(); + return this._options; + } + get config() { + this.checkDestroyed(); + return this._config; + } + get container() { + return this._container; + } + get isDeleted() { + return this._isDeleted; + } + set isDeleted(val) { + this._isDeleted = val; + } + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + checkDestroyed() { + if (this.isDeleted) { + throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name }); + } + } + } + + /** + * @license + * Copyright 2023 Google LLC + * + * 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. + */ + class FirebaseServerAppImpl extends FirebaseAppImpl { + constructor(options, serverConfig, name, container) { + // Build configuration parameters for the FirebaseAppImpl base class. + const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined + ? serverConfig.automaticDataCollectionEnabled + : false; + // Create the FirebaseAppSettings object for the FirebaseAppImp constructor. + const config = { + name, + automaticDataCollectionEnabled + }; + if (options.apiKey !== undefined) { + // Construct the parent FirebaseAppImp object. + super(options, config, container); + } + else { + const appImpl = options; + super(appImpl.options, config, container); + } + // Now construct the data for the FirebaseServerAppImpl. + this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig); + this._finalizationRegistry = null; + if (typeof FinalizationRegistry !== 'undefined') { + this._finalizationRegistry = new FinalizationRegistry(() => { + this.automaticCleanup(); + }); + } + this._refCount = 0; + this.incRefCount(this._serverConfig.releaseOnDeref); + // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry + // will never trigger. + this._serverConfig.releaseOnDeref = undefined; + serverConfig.releaseOnDeref = undefined; + registerVersion(name$q, version$1, 'serverapp'); + } + toJSON() { + return undefined; + } + get refCount() { + return this._refCount; + } + // Increment the reference count of this server app. If an object is provided, register it + // with the finalization registry. + incRefCount(obj) { + if (this.isDeleted) { + return; + } + this._refCount++; + if (obj !== undefined && this._finalizationRegistry !== null) { + this._finalizationRegistry.register(obj, this); + } + } + // Decrement the reference count. + decRefCount() { + if (this.isDeleted) { + return 0; + } + return --this._refCount; + } + // Invoked by the FinalizationRegistry callback to note that this app should go through its + // reference counts and delete itself if no reference count remain. The coordinating logic that + // handles this is in deleteApp(...). + automaticCleanup() { + void deleteApp(this); + } + get settings() { + this.checkDestroyed(); + return this._serverConfig; + } + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + checkDestroyed() { + if (this.isDeleted) { + throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */); + } + } + } + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + /** + * The current SDK version. + * + * @public + */ + const SDK_VERSION = version; + function initializeApp(_options, rawConfig = {}) { + let options = _options; + if (typeof rawConfig !== 'object') { + const name = rawConfig; + rawConfig = { name }; + } + const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig); + const name = config.name; + if (typeof name !== 'string' || !name) { + throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, { + appName: String(name) + }); + } + options || (options = getDefaultAppConfig()); + if (!options) { + throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */); + } + const existingApp = _apps.get(name); + if (existingApp) { + // return the existing app if options and config deep equal the ones in the existing app. + if (deepEqual(options, existingApp.options) && + deepEqual(config, existingApp.config)) { + return existingApp; + } + else { + throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name }); + } + } + const container = new ComponentContainer(name); + for (const component of _components.values()) { + container.addComponent(component); + } + const newApp = new FirebaseAppImpl(options, config, container); + _apps.set(name, newApp); + return newApp; + } + function initializeServerApp(_options, _serverAppConfig) { + if (isBrowser() && !isWebWorker()) { + // FirebaseServerApp isn't designed to be run in browsers. + throw ERROR_FACTORY.create("invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */); + } + if (_serverAppConfig.automaticDataCollectionEnabled === undefined) { + _serverAppConfig.automaticDataCollectionEnabled = false; + } + let appOptions; + if (_isFirebaseApp(_options)) { + appOptions = _options.options; + } + else { + appOptions = _options; + } + // Build an app name based on a hash of the configuration options. + const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions); + // However, Do not mangle the name based on releaseOnDeref, since it will vary between the + // construction of FirebaseServerApp instances. For example, if the object is the request headers. + if (nameObj.releaseOnDeref !== undefined) { + delete nameObj.releaseOnDeref; + } + const hashCode = (s) => { + return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0); + }; + if (_serverAppConfig.releaseOnDeref !== undefined) { + if (typeof FinalizationRegistry === 'undefined') { + throw ERROR_FACTORY.create("finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {}); + } + } + const nameString = '' + hashCode(JSON.stringify(nameObj)); + const existingApp = _serverApps.get(nameString); + if (existingApp) { + existingApp.incRefCount(_serverAppConfig.releaseOnDeref); + return existingApp; + } + const container = new ComponentContainer(nameString); + for (const component of _components.values()) { + container.addComponent(component); + } + const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container); + _serverApps.set(nameString, newApp); + return newApp; + } + /** + * Retrieves a {@link @firebase/app#FirebaseApp} instance. + * + * When called with no arguments, the default app is returned. When an app name + * is provided, the app corresponding to that name is returned. + * + * An exception is thrown if the app being retrieved has not yet been + * initialized. + * + * @example + * ```javascript + * // Return the default app + * const app = getApp(); + * ``` + * + * @example + * ```javascript + * // Return a named app + * const otherApp = getApp("otherApp"); + * ``` + * + * @param name - Optional name of the app to return. If no name is + * provided, the default is `"[DEFAULT]"`. + * + * @returns The app corresponding to the provided app name. + * If no app name is provided, the default app is returned. + * + * @public + */ + function getApp(name = DEFAULT_ENTRY_NAME) { + const app = _apps.get(name); + if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) { + return initializeApp(); + } + if (!app) { + throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name }); + } + return app; + } + /** + * A (read-only) array of all initialized apps. + * @public + */ + function getApps() { + return Array.from(_apps.values()); + } + /** + * Renders this app unusable and frees the resources of all associated + * services. + * + * @example + * ```javascript + * deleteApp(app) + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + * + * @public + */ + async function deleteApp(app) { + let cleanupProviders = false; + const name = app.name; + if (_apps.has(name)) { + cleanupProviders = true; + _apps.delete(name); + } + else if (_serverApps.has(name)) { + const firebaseServerApp = app; + if (firebaseServerApp.decRefCount() <= 0) { + _serverApps.delete(name); + cleanupProviders = true; + } + } + if (cleanupProviders) { + await Promise.all(app.container + .getProviders() + .map(provider => provider.delete())); + app.isDeleted = true; + } + } + /** + * Registers a library's name and version for platform logging purposes. + * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) + * @param version - Current version of that library. + * @param variant - Bundle variant, e.g., node, rn, etc. + * + * @public + */ + function registerVersion(libraryKeyOrName, version, variant) { + var _a; + // TODO: We can use this check to whitelist strings when/if we set up + // a good whitelist system. + let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName; + if (variant) { + library += `-${variant}`; + } + const libraryMismatch = library.match(/\s|\//); + const versionMismatch = version.match(/\s|\//); + if (libraryMismatch || versionMismatch) { + const warning = [ + `Unable to register library "${library}" with version "${version}":` + ]; + if (libraryMismatch) { + warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`); + } + if (libraryMismatch && versionMismatch) { + warning.push('and'); + } + if (versionMismatch) { + warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`); + } + logger.warn(warning.join(' ')); + return; + } + _registerComponent(new Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */)); + } + /** + * Sets log handler for all Firebase SDKs. + * @param logCallback - An optional custom log handler that executes user code whenever + * the Firebase SDK makes a logging call. + * + * @public + */ + function onLog(logCallback, options) { + if (logCallback !== null && typeof logCallback !== 'function') { + throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */); + } + index_cjs.setUserLogHandler(logCallback, options); + } + /** + * Sets log level for all Firebase SDKs. + * + * All of the log types above the current log level are captured (i.e. if + * you set the log level to `info`, errors are logged, but `debug` and + * `verbose` logs are not). + * + * @public + */ + function setLogLevel(logLevel) { + index_cjs.setLogLevel(logLevel); + } + + /** + * @license + * Copyright 2021 Google LLC + * + * 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. + */ + const DB_NAME = 'firebase-heartbeat-database'; + const DB_VERSION = 1; + const STORE_NAME = 'firebase-heartbeat-store'; + let dbPromise = null; + function getDbPromise() { + if (!dbPromise) { + dbPromise = openDB(DB_NAME, DB_VERSION, { + upgrade: (db, oldVersion) => { + // We don't use 'break' in this switch statement, the fall-through + // behavior is what we want, because if there are multiple versions between + // the old version and the current version, we want ALL the migrations + // that correspond to those versions to run, not only the last one. + // eslint-disable-next-line default-case + switch (oldVersion) { + case 0: + try { + db.createObjectStore(STORE_NAME); + } + catch (e) { + // Safari/iOS browsers throw occasional exceptions on + // db.createObjectStore() that may be a bug. Avoid blocking + // the rest of the app functionality. + console.warn(e); + } + } + } + }).catch(e => { + throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, { + originalErrorMessage: e.message + }); + }); + } + return dbPromise; + } + async function readHeartbeatsFromIndexedDB(app) { + try { + const db = await getDbPromise(); + const tx = db.transaction(STORE_NAME); + const result = await tx.objectStore(STORE_NAME).get(computeKey(app)); + // We already have the value but tx.done can throw, + // so we need to await it here to catch errors + await tx.done; + return result; + } + catch (e) { + if (e instanceof FirebaseError) { + logger.warn(e.message); + } + else { + const idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, { + originalErrorMessage: e === null || e === void 0 ? void 0 : e.message + }); + logger.warn(idbGetError.message); + } + } + } + async function writeHeartbeatsToIndexedDB(app, heartbeatObject) { + try { + const db = await getDbPromise(); + const tx = db.transaction(STORE_NAME, 'readwrite'); + const objectStore = tx.objectStore(STORE_NAME); + await objectStore.put(heartbeatObject, computeKey(app)); + await tx.done; + } + catch (e) { + if (e instanceof FirebaseError) { + logger.warn(e.message); + } + else { + const idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, { + originalErrorMessage: e === null || e === void 0 ? void 0 : e.message + }); + logger.warn(idbGetError.message); + } + } + } + function computeKey(app) { + return `${app.name}!${app.options.appId}`; + } + + /** + * @license + * Copyright 2021 Google LLC + * + * 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. + */ + const MAX_HEADER_BYTES = 1024; + // 30 days + const STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000; + class HeartbeatServiceImpl { + constructor(container) { + this.container = container; + /** + * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate + * the header string. + * Stores one record per date. This will be consolidated into the standard + * format of one record per user agent string before being sent as a header. + * Populated from indexedDB when the controller is instantiated and should + * be kept in sync with indexedDB. + * Leave public for easier testing. + */ + this._heartbeatsCache = null; + const app = this.container.getProvider('app').getImmediate(); + this._storage = new HeartbeatStorageImpl(app); + this._heartbeatsCachePromise = this._storage.read().then(result => { + this._heartbeatsCache = result; + return result; + }); + } + /** + * Called to report a heartbeat. The function will generate + * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it + * to IndexedDB. + * Note that we only store one heartbeat per day. So if a heartbeat for today is + * already logged, subsequent calls to this function in the same day will be ignored. + */ + async triggerHeartbeat() { + var _a, _b; + try { + const platformLogger = this.container + .getProvider('platform-logger') + .getImmediate(); + // This is the "Firebase user agent" string from the platform logger + // service, not the browser user agent. + const agent = platformLogger.getPlatformInfoString(); + const date = getUTCDateString(); + if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) { + this._heartbeatsCache = await this._heartbeatsCachePromise; + // If we failed to construct a heartbeats cache, then return immediately. + if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) { + return; + } + } + // Do not store a heartbeat if one is already stored for this day + // or if a header has already been sent today. + if (this._heartbeatsCache.lastSentHeartbeatDate === date || + this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) { + return; + } + else { + // There is no entry for this date. Create one. + this._heartbeatsCache.heartbeats.push({ date, agent }); + } + // Remove entries older than 30 days. + this._heartbeatsCache.heartbeats = + this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => { + const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf(); + const now = Date.now(); + return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS; + }); + return this._storage.overwrite(this._heartbeatsCache); + } + catch (e) { + logger.warn(e); + } + } + /** + * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly. + * It also clears all heartbeats from memory as well as in IndexedDB. + * + * NOTE: Consuming product SDKs should not send the header if this method + * returns an empty string. + */ + async getHeartbeatsHeader() { + var _a; + try { + if (this._heartbeatsCache === null) { + await this._heartbeatsCachePromise; + } + // If it's still null or the array is empty, there is no data to send. + if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null || + this._heartbeatsCache.heartbeats.length === 0) { + return ''; + } + const date = getUTCDateString(); + // Extract as many heartbeats from the cache as will fit under the size limit. + const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats); + const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })); + // Store last sent date to prevent another being logged/sent for the same day. + this._heartbeatsCache.lastSentHeartbeatDate = date; + if (unsentEntries.length > 0) { + // Store any unsent entries if they exist. + this._heartbeatsCache.heartbeats = unsentEntries; + // This seems more likely than emptying the array (below) to lead to some odd state + // since the cache isn't empty and this will be called again on the next request, + // and is probably safest if we await it. + await this._storage.overwrite(this._heartbeatsCache); + } + else { + this._heartbeatsCache.heartbeats = []; + // Do not wait for this, to reduce latency. + void this._storage.overwrite(this._heartbeatsCache); + } + return headerString; + } + catch (e) { + logger.warn(e); + return ''; + } + } + } + function getUTCDateString() { + const today = new Date(); + // Returns date format 'YYYY-MM-DD' + return today.toISOString().substring(0, 10); + } + function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) { + // Heartbeats grouped by user agent in the standard format to be sent in + // the header. + const heartbeatsToSend = []; + // Single date format heartbeats that are not sent. + let unsentEntries = heartbeatsCache.slice(); + for (const singleDateHeartbeat of heartbeatsCache) { + // Look for an existing entry with the same user agent. + const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent); + if (!heartbeatEntry) { + // If no entry for this user agent exists, create one. + heartbeatsToSend.push({ + agent: singleDateHeartbeat.agent, + dates: [singleDateHeartbeat.date] + }); + if (countBytes(heartbeatsToSend) > maxSize) { + // If the header would exceed max size, remove the added heartbeat + // entry and stop adding to the header. + heartbeatsToSend.pop(); + break; + } + } + else { + heartbeatEntry.dates.push(singleDateHeartbeat.date); + // If the header would exceed max size, remove the added date + // and stop adding to the header. + if (countBytes(heartbeatsToSend) > maxSize) { + heartbeatEntry.dates.pop(); + break; + } + } + // Pop unsent entry from queue. (Skipped if adding the entry exceeded + // quota and the loop breaks early.) + unsentEntries = unsentEntries.slice(1); + } + return { + heartbeatsToSend, + unsentEntries + }; + } + class HeartbeatStorageImpl { + constructor(app) { + this.app = app; + this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck(); + } + async runIndexedDBEnvironmentCheck() { + if (!isIndexedDBAvailable()) { + return false; + } + else { + return validateIndexedDBOpenable() + .then(() => true) + .catch(() => false); + } + } + /** + * Read all heartbeats. + */ + async read() { + const canUseIndexedDB = await this._canUseIndexedDBPromise; + if (!canUseIndexedDB) { + return { heartbeats: [] }; + } + else { + const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app); + if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) { + return idbHeartbeatObject; + } + else { + return { heartbeats: [] }; + } + } + } + // overwrite the storage with the provided heartbeats + async overwrite(heartbeatsObject) { + var _a; + const canUseIndexedDB = await this._canUseIndexedDBPromise; + if (!canUseIndexedDB) { + return; + } + else { + const existingHeartbeatsObject = await this.read(); + return writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: heartbeatsObject.heartbeats + }); + } + } + // add heartbeats + async add(heartbeatsObject) { + var _a; + const canUseIndexedDB = await this._canUseIndexedDBPromise; + if (!canUseIndexedDB) { + return; + } + else { + const existingHeartbeatsObject = await this.read(); + return writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: [ + ...existingHeartbeatsObject.heartbeats, + ...heartbeatsObject.heartbeats + ] + }); + } + } + } + /** + * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped + * in a platform logging header JSON object, stringified, and converted + * to base 64. + */ + function countBytes(heartbeatsCache) { + // base64 has a restricted set of characters, all of which should be 1 byte. + return base64urlEncodeWithoutPadding( + // heartbeatsCache wrapper properties + JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length; + } + + /** + * @license + * Copyright 2019 Google LLC + * + * 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. + */ + function registerCoreComponents(variant) { + _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */)); + _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */)); + // Register `app` package. + registerVersion(name$q, version$1, variant); + // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation + registerVersion(name$q, version$1, 'esm2017'); + // Register platform SDK identifier (no version). + registerVersion('fire-js', ''); + } + + /** + * Firebase App + * + * @remarks This package coordinates the communication between the different Firebase components + * @packageDocumentation + */ + registerCoreComponents(''); + + exports.Component = Component; + exports.DEFAULT_ENTRY_NAME = DEFAULT_ENTRY_NAME; + exports.FirebaseError = FirebaseError; + exports.SDK_VERSION = SDK_VERSION; + exports._addComponent = _addComponent; + exports._addOrOverwriteComponent = _addOrOverwriteComponent; + exports._apps = _apps; + exports._clearComponents = _clearComponents; + exports._components = _components; + exports._getProvider = _getProvider; + exports._isFirebaseApp = _isFirebaseApp; + exports._isFirebaseServerApp = _isFirebaseServerApp; + exports._registerComponent = _registerComponent; + exports._removeServiceInstance = _removeServiceInstance; + exports._serverApps = _serverApps; + exports.createMockUserToken = createMockUserToken; + exports.deepEqual = deepEqual; + exports.deleteApp = deleteApp; + exports.getApp = getApp; + exports.getApps = getApps; + exports.getDefaultEmulatorHostnameAndPort = getDefaultEmulatorHostnameAndPort; + exports.getModularInstance = getModularInstance; + exports.index_cjs = index_cjs; + exports.initializeApp = initializeApp; + exports.initializeServerApp = initializeServerApp; + exports.onLog = onLog; + exports.registerVersion = registerVersion; + exports.setLogLevel = setLogLevel; + +})); diff --git a/packages/ui5-tooling-modules/test/__snap__/4370bd2f/@ui5/webcomponents/dist/CheckBox.js b/packages/ui5-tooling-modules/test/__snap__/4370bd2f/@ui5/webcomponents/dist/CheckBox.js index 86fc5fc7..0e42bbe8 100644 --- a/packages/ui5-tooling-modules/test/__snap__/4370bd2f/@ui5/webcomponents/dist/CheckBox.js +++ b/packages/ui5-tooling-modules/test/__snap__/4370bd2f/@ui5/webcomponents/dist/CheckBox.js @@ -1,6850 +1,3276 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/@ui5/webcomponents', 'sap/ui/core/webc/WebComponent', 'sap/ui/core/EnabledPropagator', 'ui5/ecosystem/demo/app/resources/@ui5/webcomponents-base', 'sap/base/strings/hyphenate', 'sap/ui/base/DataType'], (function (_ui5_webcomponents, WebComponent, EnabledPropagator, _ui5_webcomponentsBase, hyphenate, DataType) { 'use strict'; - var class2type = {}; - var hasOwn = class2type.hasOwnProperty; - var toString = class2type.toString; - var fnToString = hasOwn.toString; - var ObjectFunctionString = fnToString.call(Object); - var fnIsPlainObject = function (obj) { - var proto, Ctor; - if (!obj || toString.call(obj) !== "[object Object]") { - return false; - } - proto = Object.getPrototypeOf(obj); - if (!proto) { - return true; - } - Ctor = hasOwn.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString; - }; + var c$l={},e$i=c$l.hasOwnProperty,a$g=c$l.toString,o$n=e$i.toString,l$j=o$n.call(Object),i$o=function(r){var t,n;return !r||a$g.call(r)!=="[object Object]"?!1:(t=Object.getPrototypeOf(r),t?(n=e$i.call(t,"constructor")&&t.constructor,typeof n=="function"&&o$n.call(n)===l$j):!0)}; - var oToken = Object.create(null); - var fnMerge$1 = function (arg1, arg2, arg3, arg4) { - var src, copyIsArray, copy, name, options, clone, target = arguments[2] || {}, i = 3, length = arguments.length, deep = arguments[0] || false, skipToken = arguments[1] ? undefined : oToken; - if (typeof target !== 'object' && typeof target !== 'function') { - target = {}; - } - for (; i < length; i++) { - if ((options = arguments[i]) != null) { - for (name in options) { - src = target[name]; - copy = options[name]; - if (name === '__proto__' || target === copy) { - continue; - } - if (deep && copy && (fnIsPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && Array.isArray(src) ? src : []; - } - else { - clone = src && fnIsPlainObject(src) ? src : {}; - } - target[name] = fnMerge$1(deep, arguments[1], clone, copy); - } - else if (copy !== skipToken) { - target[name] = copy; - } - } - } - } - return target; - }; + var c$k=Object.create(null),u$g=function(p,m,A,d){var n,t,e,a,o,i,r=arguments[2]||{},f=3,l=arguments.length,s=arguments[0]||!1,y=arguments[1]?void 0:c$k;for(typeof r!="object"&&typeof r!="function"&&(r={});f { - return fn.call(this, data); - }); - } - /** - * Fires an event and returns a promise that will resolve once all listeners have resolved. - * - * @param eventName the event to fire - * @param data optional data to pass to each event listener - * @returns {Promise} a promise that will resolve when all listeners have resolved - */ - fireEventAsync(eventName, data) { - return Promise.all(this.fireEvent(eventName, data)); - } - isHandlerAttached(eventName, fnFunction) { - const eventRegistry = this._eventRegistry; - const eventListeners = eventRegistry.get(eventName); - if (!eventListeners) { - return false; - } - return eventListeners.includes(fnFunction); - } - hasListeners(eventName) { - return !!this._eventRegistry.get(eventName); - } - } + let i$n = class i{constructor(){this._eventRegistry=new Map;}attachEvent(t,r){const n=this._eventRegistry,e=n.get(t);if(!Array.isArray(e)){n.set(t,[r]);return}e.includes(r)||e.push(r);}detachEvent(t,r){const n=this._eventRegistry,e=n.get(t);if(!e)return;const s=e.indexOf(r);s!==-1&&e.splice(s,1),e.length===0&&n.delete(t);}fireEvent(t,r){const e=this._eventRegistry.get(t);return e?e.map(s=>s.call(this,r)):[]}fireEventAsync(t,r){return Promise.all(this.fireEvent(t,r))}isHandlerAttached(t,r){const e=this._eventRegistry.get(t);return e?e.includes(r):!1}hasListeners(t){return !!this._eventRegistry.get(t)}}; - const features = new Map(); - const componentFeatures = new Map(); - const subscribers = new Map(); - const EVENT_NAME = "componentFeatureLoad"; - const eventProvider$6 = new EventProvider(); - const featureLoadEventName = name => `${EVENT_NAME}_${name}`; - const registerFeature = (name, feature) => { - features.set(name, feature); - }; - const getFeature = name => { - return features.get(name); - }; - const getComponentFeature = name => { - return componentFeatures.get(name); - }; - const subscribeForFeatureLoad = (name, klass, callback) => { - const subscriber = subscribers.get(klass); - const isSubscribed = subscriber?.includes(name); - if (isSubscribed) { - return; - } - if (!subscriber) { - subscribers.set(klass, [name]); - } else { - subscriber.push(name); - } - eventProvider$6.attachEvent(featureLoadEventName(name), callback); - }; + const s$q = new Map(), o$m = new Map(), i$m = new Map(), p$a = "componentFeatureLoad", a$f = new i$n(), c$j = e => `${p$a}_${e}`, g$9 = (e, t) => { + s$q.set(e, t); + }, m$d = e => s$q.get(e), F$1 = e => o$m.get(e), b$7 = (e, t, n) => { + const r = i$m.get(t); + r?.includes(e) || (r ? r.push(e) : i$m.set(t, [e]), a$f.attachEvent(c$j(e), n)); + }; - const assetParameters = { "themes": { "default": "sap_horizon", "all": ["sap_fiori_3", "sap_fiori_3_dark", "sap_fiori_3_hcb", "sap_fiori_3_hcw", "sap_horizon", "sap_horizon_dark", "sap_horizon_hcb", "sap_horizon_hcw", "sap_horizon_exp", "sap_horizon_dark_exp", "sap_horizon_hcb_exp", "sap_horizon_hcw_exp"] }, "languages": { "default": "en", "all": ["ar", "bg", "ca", "cnr", "cs", "cy", "da", "de", "el", "en", "en_GB", "en_US_sappsd", "en_US_saprigi", "en_US_saptrc", "es", "es_MX", "et", "fi", "fr", "fr_CA", "hi", "hr", "hu", "in", "it", "iw", "ja", "kk", "ko", "lt", "lv", "mk", "ms", "nl", "no", "pl", "pt_PT", "pt", "ro", "ru", "sh", "sk", "sl", "sr", "sv", "th", "tr", "uk", "vi", "zh_CN", "zh_TW"] }, "locales": { "default": "en", "all": ["ar", "ar_EG", "ar_SA", "bg", "ca", "cnr", "cs", "da", "de", "de_AT", "de_CH", "el", "el_CY", "en", "en_AU", "en_GB", "en_HK", "en_IE", "en_IN", "en_NZ", "en_PG", "en_SG", "en_ZA", "es", "es_AR", "es_BO", "es_CL", "es_CO", "es_MX", "es_PE", "es_UY", "es_VE", "et", "fa", "fi", "fr", "fr_BE", "fr_CA", "fr_CH", "fr_LU", "he", "hi", "hr", "hu", "id", "it", "it_CH", "ja", "kk", "ko", "lt", "lv", "ms", "mk", "nb", "nl", "nl_BE", "pl", "pt", "pt_PT", "ro", "ru", "ru_UA", "sk", "sl", "sr", "sr_Latn", "sv", "th", "tr", "uk", "vi", "zh_CN", "zh_HK", "zh_SG", "zh_TW"] } }; - const DEFAULT_THEME = assetParameters.themes.default; - const SUPPORTED_THEMES = assetParameters.themes.all; - const DEFAULT_LANGUAGE = assetParameters.languages.default; - const DEFAULT_LOCALE = assetParameters.locales.default; - const SUPPORTED_LOCALES = assetParameters.locales.all; - - const isSSR$3 = typeof document === "undefined"; - const internals$1 = { - search() { - if (isSSR$3) { - return ""; - } - return window.location.search; - }, - }; - const getLocationHref = () => { - if (isSSR$3) { - return ""; - } - return window.location.href; - }; - const getLocationSearch = () => { - return internals$1.search(); - }; + const _$4={themes:{default:"sap_horizon",all:["sap_fiori_3","sap_fiori_3_dark","sap_fiori_3_hcb","sap_fiori_3_hcw","sap_horizon","sap_horizon_dark","sap_horizon_hcb","sap_horizon_hcw","sap_horizon_exp","sap_horizon_dark_exp","sap_horizon_hcb_exp","sap_horizon_hcw_exp"]},languages:{default:"en",all:["ar","bg","ca","cnr","cs","cy","da","de","el","en","en_GB","en_US_sappsd","en_US_saprigi","en_US_saptrc","es","es_MX","et","fi","fr","fr_CA","hi","hr","hu","in","it","iw","ja","kk","ko","lt","lv","mk","ms","nl","no","pl","pt_PT","pt","ro","ru","sh","sk","sl","sr","sv","th","tr","uk","vi","zh_CN","zh_TW"]},locales:{default:"en",all:["ar","ar_EG","ar_SA","bg","ca","cnr","cs","da","de","de_AT","de_CH","el","el_CY","en","en_AU","en_GB","en_HK","en_IE","en_IN","en_NZ","en_PG","en_SG","en_ZA","es","es_AR","es_BO","es_CL","es_CO","es_MX","es_PE","es_UY","es_VE","et","fa","fi","fr","fr_BE","fr_CA","fr_CH","fr_LU","he","hi","hr","hu","id","it","it_CH","ja","kk","ko","lt","lv","ms","mk","nb","nl","nl_BE","pl","pt","pt_PT","ro","ru","ru_UA","sk","sl","sr","sr_Latn","sv","th","tr","uk","vi","zh_CN","zh_HK","zh_SG","zh_TW"]}},e$g=_$4.themes.default,s$p=_$4.themes.all,a$e=_$4.languages.default,r$j=_$4.locales.default,n$k=_$4.locales.all; - const getMetaTagValue = (metaTagName) => { - const metaTag = document.querySelector(`META[name="${metaTagName}"]`), metaTagContent = metaTag && metaTag.getAttribute("content"); - return metaTagContent; - }; - const validateThemeOrigin = (origin) => { - const allowedOrigins = getMetaTagValue("sap-allowedThemeOrigins"); - return allowedOrigins && allowedOrigins.split(",").some(allowedOrigin => { - return allowedOrigin === "*" || origin === allowedOrigin.trim(); - }); - }; - const buildCorrectUrl = (oldUrl, newOrigin) => { - const oldUrlPath = new URL(oldUrl).pathname; - return new URL(oldUrlPath, newOrigin).toString(); - }; - const validateThemeRoot = (themeRoot) => { - let resultUrl; - try { - if (themeRoot.startsWith(".") || themeRoot.startsWith("/")) { - // Handle relative url - // new URL("/newExmPath", "http://example.com/exmPath") => http://example.com/newExmPath - // new URL("./newExmPath", "http://example.com/exmPath") => http://example.com/exmPath/newExmPath - // new URL("../newExmPath", "http://example.com/exmPath") => http://example.com/newExmPath - resultUrl = new URL(themeRoot, getLocationHref()).toString(); - } - else { - const themeRootURL = new URL(themeRoot); - const origin = themeRootURL.origin; - if (origin && validateThemeOrigin(origin)) { - // If origin is allowed, use it - resultUrl = themeRootURL.toString(); - } - else { - // If origin is not allow and the URL is not relative, we have to replace the origin - // with current location - resultUrl = buildCorrectUrl(themeRootURL.toString(), getLocationHref()); - } - } - if (!resultUrl.endsWith("/")) { - resultUrl = `${resultUrl}/`; - } - return `${resultUrl}UI5/`; - } - catch (e) { - // Catch if URL is not correct - } - }; + const o$l=typeof document>"u",n$j={search(){return o$l?"":window.location.search}},s$o=()=>o$l?"":window.location.href,u$f=()=>n$j.search(); - /** - * Different types of AnimationMode. - * - * @public - */ - var AnimationMode; - (function (AnimationMode) { - /** - * @public - */ - AnimationMode["Full"] = "full"; - /** - * @public - */ - AnimationMode["Basic"] = "basic"; - /** - * @public - */ - AnimationMode["Minimal"] = "minimal"; - /** - * @public - */ - AnimationMode["None"] = "none"; - })(AnimationMode || (AnimationMode = {})); - var AnimationMode$1 = AnimationMode; - - const eventProvider$5 = new EventProvider(); - const CONFIGURATION_RESET = "configurationReset"; - const attachConfigurationReset = (listener) => { - eventProvider$5.attachEvent(CONFIGURATION_RESET, listener); - }; + const o$k=e=>{const t=document.querySelector(`META[name="${e}"]`);return t&&t.getAttribute("content")},s$n=e=>{const t=o$k("sap-allowedThemeOrigins");return t&&t.split(",").some(n=>n==="*"||e===n.trim())},a$d=(e,t)=>{const n=new URL(e).pathname;return new URL(n,t).toString()},g$8=e=>{let t;try{if(e.startsWith(".")||e.startsWith("/"))t=new URL(e,s$o()).toString();else {const n=new URL(e),r=n.origin;r&&s$n(r)?t=n.toString():t=a$d(n.toString(),s$o());}return t.endsWith("/")||(t=`${t}/`),`${t}UI5/`}catch{}}; - let initialized = false; - let initialConfig = { - animationMode: AnimationMode$1.Full, - theme: DEFAULT_THEME, - themeRoot: undefined, - rtl: undefined, - language: undefined, - timezone: undefined, - calendarType: undefined, - secondaryCalendarType: undefined, - noConflict: false, // no URL - formatSettings: {}, - fetchDefaultLanguage: false, - defaultFontLoading: true, - enableDefaultTooltips: true, - }; - const getTheme$1 = () => { - initConfiguration(); - return initialConfig.theme; - }; - const getThemeRoot$1 = () => { - initConfiguration(); - return initialConfig.themeRoot; - }; - const getLanguage$1 = () => { - initConfiguration(); - return initialConfig.language; - }; - /** - * Returns if the default language, that is inlined at build time, - * should be fetched over the network instead. - * @returns {Boolean} - */ - const getFetchDefaultLanguage$1 = () => { - initConfiguration(); - return initialConfig.fetchDefaultLanguage; - }; - const getNoConflict$1 = () => { - initConfiguration(); - return initialConfig.noConflict; - }; - const getDefaultFontLoading$1 = () => { - initConfiguration(); - return initialConfig.defaultFontLoading; - }; - const getFormatSettings = () => { - initConfiguration(); - return initialConfig.formatSettings; - }; - const booleanMapping = new Map(); - booleanMapping.set("true", true); - booleanMapping.set("false", false); - const parseConfigurationScript = () => { - const configScript = document.querySelector("[data-ui5-config]") || document.querySelector("[data-id='sap-ui-config']"); // for backward compatibility - let configJSON; - if (configScript) { - try { - configJSON = JSON.parse(configScript.innerHTML); - } - catch (err) { - console.warn("Incorrect data-sap-ui-config format. Please use JSON"); /* eslint-disable-line */ - } - if (configJSON) { - initialConfig = fnMerge(initialConfig, configJSON); - } - } - }; - const parseURLParameters = () => { - const params = new URLSearchParams(getLocationSearch()); - // Process "sap-*" params first - params.forEach((value, key) => { - const parts = key.split("sap-").length; - if (parts === 0 || parts === key.split("sap-ui-").length) { - return; - } - applyURLParam(key, value, "sap"); - }); - // Process "sap-ui-*" params - params.forEach((value, key) => { - if (!key.startsWith("sap-ui")) { - return; - } - applyURLParam(key, value, "sap-ui"); - }); - }; - const normalizeThemeRootParamValue = (value) => { - const themeRoot = value.split("@")[1]; - return validateThemeRoot(themeRoot); - }; - const normalizeThemeParamValue = (param, value) => { - if (param === "theme" && value.includes("@")) { // the theme parameter might have @ in the value - strip this - return value.split("@")[0]; - } - return value; - }; - const applyURLParam = (key, value, paramType) => { - const lowerCaseValue = value.toLowerCase(); - const param = key.split(`${paramType}-`)[1]; - if (booleanMapping.has(value)) { - value = booleanMapping.get(lowerCaseValue); - } - if (param === "theme") { - initialConfig.theme = normalizeThemeParamValue(param, value); - if (value && value.includes("@")) { - initialConfig.themeRoot = normalizeThemeRootParamValue(value); - } - } - else { - initialConfig[param] = value; - } - }; - const applyOpenUI5Configuration = () => { - const openUI5Support = getFeature("OpenUI5Support"); - if (!openUI5Support || !openUI5Support.isOpenUI5Detected()) { - return; - } - const OpenUI5Config = openUI5Support.getConfigurationSettingsObject(); - initialConfig = fnMerge(initialConfig, OpenUI5Config); - }; - const initConfiguration = () => { - if (typeof document === "undefined" || initialized) { - return; - } - resetConfiguration(); - initialized = true; - }; - /** - * Internaly exposed method to enable configurations in tests. - * @private - */ - const resetConfiguration = (testEnv) => { - // 1. Lowest priority - configuration script - parseConfigurationScript(); - // 2. URL parameters overwrite configuration script parameters - parseURLParameters(); - // 3. If OpenUI5 is detected, it has the highest priority - applyOpenUI5Configuration(); - }; + var u$e=(l=>(l.Full="full",l.Basic="basic",l.Minimal="minimal",l.None="none",l))(u$e||{}); - attachConfigurationReset(() => { - }); + const e$f=new i$n,t$m="configurationReset",i$l=n=>{e$f.attachEvent(t$m,n);}; - /** - * Different calendar types. - * - * @public - */ - var CalendarType; - (function (CalendarType) { - /** - * @public - */ - CalendarType["Gregorian"] = "Gregorian"; - /** - * @public - */ - CalendarType["Islamic"] = "Islamic"; - /** - * @public - */ - CalendarType["Japanese"] = "Japanese"; - /** - * @public - */ - CalendarType["Buddhist"] = "Buddhist"; - /** - * @public - */ - CalendarType["Persian"] = "Persian"; - })(CalendarType || (CalendarType = {})); - - attachConfigurationReset(() => { - }); - - let formatSettings; - class LegacyDateFormats { - /** - * Returns the currently set customizing data for Islamic calendar support - * - * @return {object[]} Returns an array that contains the customizing data. - * @public - */ - static getLegacyDateCalendarCustomizing() { - if (formatSettings === undefined) { - formatSettings = getFormatSettings(); - } - return formatSettings.legacyDateCalendarCustomizing || []; - } - } - registerFeature("LegacyDateFormats", LegacyDateFormats); + let p$9=!1,t$l={animationMode:u$e.Full,theme:e$g,themeRoot:void 0,rtl:void 0,language:void 0,timezone:void 0,calendarType:void 0,secondaryCalendarType:void 0,noConflict:!1,formatSettings:{},fetchDefaultLanguage:!1,defaultFontLoading:!0,enableDefaultTooltips:!0};const T$1=()=>(o$j(),t$l.theme),S$6=()=>(o$j(),t$l.themeRoot),L$2=()=>(o$j(),t$l.language),F=()=>(o$j(),t$l.fetchDefaultLanguage),U$2=()=>(o$j(),t$l.noConflict),b$6=()=>(o$j(),t$l.defaultFontLoading),M$2=()=>(o$j(),t$l.formatSettings),i$k=new Map;i$k.set("true",!0),i$k.set("false",!1);const z$1=()=>{const n=document.querySelector("[data-ui5-config]")||document.querySelector("[data-id='sap-ui-config']");let e;if(n){try{e=JSON.parse(n.innerHTML);}catch{console.warn("Incorrect data-sap-ui-config format. Please use JSON");}e&&(t$l=e$h(t$l,e));}},E$3=()=>{const n=new URLSearchParams(u$f());n.forEach((e,a)=>{const r=a.split("sap-").length;r===0||r===a.split("sap-ui-").length||u$d(a,e,"sap");}),n.forEach((e,a)=>{a.startsWith("sap-ui")&&u$d(a,e,"sap-ui");});},P$4=n=>{const e=n.split("@")[1];return g$8(e)},w$6=(n,e)=>n==="theme"&&e.includes("@")?e.split("@")[0]:e,u$d=(n,e,a)=>{const r=e.toLowerCase(),s=n.split(`${a}-`)[1];i$k.has(e)&&(e=i$k.get(r)),s==="theme"?(t$l.theme=w$6(s,e),e&&e.includes("@")&&(t$l.themeRoot=P$4(e))):t$l[s]=e;},j$1=()=>{const n=m$d("OpenUI5Support");if(!n||!n.isOpenUI5Detected())return;const e=n.getConfigurationSettingsObject();t$l=e$h(t$l,e);},o$j=()=>{typeof document>"u"||p$9||(g$7(),p$9=!0);},g$7=n=>{z$1(),E$3(),j$1();}; - attachConfigurationReset(() => { - }); - const legacyDateFormats = getFeature("LegacyDateFormats"); - legacyDateFormats ? LegacyDateFormats.getLegacyDateCalendarCustomizing : () => { return []; }; + i$l(()=>{}); - const IconCollectionConfiguration = new Map(); - /** - * Returns the configured default icon collection for a given theme. - * - * @param { string } theme - * @public - * @returns { string | undefined } - */ - const getDefaultIconCollection = (theme) => { - return IconCollectionConfiguration.get(theme); - }; + var s$m=(i=>(i.Gregorian="Gregorian",i.Islamic="Islamic",i.Japanese="Japanese",i.Buddhist="Buddhist",i.Persian="Persian",i))(s$m||{}); - const MAX_PROCESS_COUNT = 10; - class RenderQueue { - constructor() { - this.list = []; // Used to store the web components in order - this.lookup = new Set(); // Used for faster search - } - add(webComponent) { - if (this.lookup.has(webComponent)) { - return; - } - this.list.push(webComponent); - this.lookup.add(webComponent); - } - remove(webComponent) { - if (!this.lookup.has(webComponent)) { - return; - } - this.list = this.list.filter(item => item !== webComponent); - this.lookup.delete(webComponent); - } - shift() { - const webComponent = this.list.shift(); - if (webComponent) { - this.lookup.delete(webComponent); - return webComponent; - } - } - isEmpty() { - return this.list.length === 0; - } - isAdded(webComponent) { - return this.lookup.has(webComponent); - } - /** - * Processes the whole queue by executing the callback on each component, - * while also imposing restrictions on how many times a component may be processed. - * - * @param callback - function with one argument (the web component to be processed) - */ - process(callback) { - let webComponent; - const stats = new Map(); - webComponent = this.shift(); - while (webComponent) { - const timesProcessed = stats.get(webComponent) || 0; - if (timesProcessed > MAX_PROCESS_COUNT) { - throw new Error(`Web component processed too many times this task, max allowed is: ${MAX_PROCESS_COUNT}`); - } - callback(webComponent); - stats.set(webComponent, timesProcessed + 1); - webComponent = this.shift(); - } - } - } + i$l(()=>{}); - /** - * Returns a singleton HTML element, inserted in given parent element of HTML page, - * used mostly to store and share global resources between multiple UI5 Web Components runtimes. - * - * @param { string } tag the element tag/selector - * @param { HTMLElement } parentElement the parent element to insert the singleton element instance - * @param { Function } createEl a factory function for the element instantiation, by default document.createElement is used - * @returns { Element } - */ - const getSingletonElementInstance = (tag, parentElement = document.body, createEl) => { - let el = document.querySelector(tag); - if (el) { - return el; - } - el = createEl ? createEl() : document.createElement(tag); - return parentElement.insertBefore(el, parentElement.firstChild); - }; + let t$k;let a$c = class a{static getLegacyDateCalendarCustomizing(){return t$k===void 0&&(t$k=M$2()),t$k.legacyDateCalendarCustomizing||[]}};g$9("LegacyDateFormats",a$c); - const getMetaDomEl = () => { - const el = document.createElement("meta"); - el.setAttribute("name", "ui5-shared-resources"); - el.setAttribute("content", ""); // attribute "content" should be present when "name" is set. - return el; - }; - const getSharedResourcesInstance = () => { - if (typeof document === "undefined") { - return null; - } - return getSingletonElementInstance(`meta[name="ui5-shared-resources"]`, document.head, getMetaDomEl); - }; - /** - * Use this method to initialize/get resources that you would like to be shared among UI5 Web Components runtime instances. - * The data will be accessed via a singleton "ui5-shared-resources" HTML element in the "body" element of the page. - * - * @public - * @param namespace Unique ID of the resource, may contain "." to denote hierarchy - * @param initialValue Object or primitive that will be used as an initial value if the resource does not exist - * @returns {*} - */ - const getSharedResource = (namespace, initialValue) => { - const parts = namespace.split("."); - let current = getSharedResourcesInstance(); - if (!current) { - return initialValue; - } - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - const lastPart = i === parts.length - 1; - if (!Object.prototype.hasOwnProperty.call(current, part)) { - current[part] = lastPart ? initialValue : {}; - } - current = current[part]; - } - return current; - }; + i$l(()=>{});const i$j=m$d("LegacyDateFormats");i$j?a$c.getLegacyDateCalendarCustomizing:()=>[]; - const VersionInfo = { - version: "2.5.0", - major: 2, - minor: 5, - patch: 0, - suffix: "", - isNext: false, - buildTime: 1733409507, - }; + const t$j=new Map,c$i=n=>t$j.get(n); - let suf; - let rulesObj = { - include: [/^ui5-/], - exclude: [], - }; - const tagsCache = new Map(); // true/false means the tag should/should not be cached, undefined means not known yet. - /** - * Returns the currently set scoping suffix, or undefined if not set. - * - * @public - * @returns {String|undefined} - */ - const getCustomElementsScopingSuffix = () => { - return suf; - }; - /** - * Returns the rules, governing which custom element tags to scope and which not. By default, all elements - * starting with "ui5-" are scoped. The default rules are: {include: [/^ui5-/]}. - * - * @public - * @returns {Object} - */ - const getCustomElementsScopingRules = () => { - return rulesObj; - }; - /** - * Determines whether custom elements with the given tag should be scoped or not. - * The tag is first matched against the "include" rules and then against the "exclude" rules and the - * result is cached until new rules are set. - * - * @public - * @param tag - */ - const shouldScopeCustomElement = (tag) => { - if (!tagsCache.has(tag)) { - const result = rulesObj.include.some(rule => tag.match(rule)) && !rulesObj.exclude.some(rule => tag.match(rule)); - tagsCache.set(tag, result); - } - return tagsCache.get(tag); - }; - /** - * Returns the currently set scoping suffix, if any and if the tag should be scoped, or undefined otherwise. - * - * @public - * @param tag - * @returns {String} - */ - const getEffectiveScopingSuffixForTag = (tag) => { - if (shouldScopeCustomElement(tag)) { - return getCustomElementsScopingSuffix(); - } - }; + let l$i = class l{constructor(){this.list=[],this.lookup=new Set;}add(t){this.lookup.has(t)||(this.list.push(t),this.lookup.add(t));}remove(t){this.lookup.has(t)&&(this.list=this.list.filter(e=>e!==t),this.lookup.delete(t));}shift(){const t=this.list.shift();if(t)return this.lookup.delete(t),t}isEmpty(){return this.list.length===0}isAdded(t){return this.lookup.has(t)}process(t){let e;const s=new Map;for(e=this.shift();e;){const i=s.get(e)||0;if(i>10)throw new Error("Web component processed too many times this task, max allowed is: 10");t(e),s.set(e,i+1),e=this.shift();}}}; - let currentRuntimeIndex; - let currentRuntimeAlias = ""; - const compareCache = new Map(); - /** - * Central registry where all runtimes register themselves by pushing an object. - * The index in the registry servers as an ID for the runtime. - * @type {*} - */ - const Runtimes = getSharedResource("Runtimes", []); - /** - * Registers the current runtime in the shared runtimes resource registry - */ - const registerCurrentRuntime = () => { - if (currentRuntimeIndex === undefined) { - currentRuntimeIndex = Runtimes.length; - const versionInfo = VersionInfo; - Runtimes.push({ - ...versionInfo, - get scopingSuffix() { - return getCustomElementsScopingSuffix(); - }, - get registeredTags() { - return getAllRegisteredTags(); - }, - get scopingRules() { - return getCustomElementsScopingRules(); - }, - alias: currentRuntimeAlias, - description: `Runtime ${currentRuntimeIndex} - ver ${versionInfo.version}${""}`, - }); - } - }; - /** - * Returns the index of the current runtime's object in the shared runtimes resource registry - * @returns {*} - */ - const getCurrentRuntimeIndex = () => { - return currentRuntimeIndex; - }; - /** - * Compares two runtimes and returns 1 if the first is of a bigger version, -1 if the second is of a bigger version, and 0 if equal - * @param index1 The index of the first runtime to compare - * @param index2 The index of the second runtime to compare - * @returns {number} - */ - const compareRuntimes = (index1, index2) => { - const cacheIndex = `${index1},${index2}`; - if (compareCache.has(cacheIndex)) { - return compareCache.get(cacheIndex); - } - const runtime1 = Runtimes[index1]; - const runtime2 = Runtimes[index2]; - if (!runtime1 || !runtime2) { - throw new Error("Invalid runtime index supplied"); - } - // If any of the two is a next version, bigger buildTime wins - if (runtime1.isNext || runtime2.isNext) { - return runtime1.buildTime - runtime2.buildTime; - } - // If major versions differ, bigger one wins - const majorDiff = runtime1.major - runtime2.major; - if (majorDiff) { - return majorDiff; - } - // If minor versions differ, bigger one wins - const minorDiff = runtime1.minor - runtime2.minor; - if (minorDiff) { - return minorDiff; - } - // If patch versions differ, bigger one wins - const patchDiff = runtime1.patch - runtime2.patch; - if (patchDiff) { - return patchDiff; - } - // Bigger suffix wins, f.e. rc10 > rc9 - // Important: suffix is alphanumeric, must use natural compare - const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }); - const result = collator.compare(runtime1.suffix, runtime2.suffix); - compareCache.set(cacheIndex, result); - return result; - }; - const getAllRuntimes = () => { - return Runtimes; - }; + const o$i=(t,n=document.body,r)=>{let e=document.querySelector(t);return e||(e=r?r():document.createElement(t),n.insertBefore(e,n.firstChild))}; - const Tags = getSharedResource("Tags", new Map()); - const Definitions = new Set(); - let Failures = new Map(); - let failureTimeout; - const UNKNOWN_RUNTIME = -1; - const registerTag = tag => { - Definitions.add(tag); - Tags.set(tag, getCurrentRuntimeIndex()); - }; - const isTagRegistered = tag => { - return Definitions.has(tag); - }; - const getAllRegisteredTags = () => { - return [...Definitions.values()]; - }; - const recordTagRegistrationFailure = tag => { - let tagRegRuntimeIndex = Tags.get(tag); - if (tagRegRuntimeIndex === undefined) { - tagRegRuntimeIndex = UNKNOWN_RUNTIME; - } - if (!Failures.has(tagRegRuntimeIndex)) { - Failures.set(tagRegRuntimeIndex, new Set()); - } - Failures.get(tagRegRuntimeIndex).add(tag); - if (!failureTimeout) { - failureTimeout = setTimeout(() => { - displayFailedRegistrations(); - Failures = new Map(); - failureTimeout = undefined; - }, 1000); - } - }; - const displayFailedRegistrations = () => { - const allRuntimes = getAllRuntimes(); - const currentRuntimeIndex = getCurrentRuntimeIndex(); - const currentRuntime = allRuntimes[currentRuntimeIndex]; - let message = `Multiple UI5 Web Components instances detected.`; - if (allRuntimes.length > 1) { - message = `${message}\nLoading order (versions before 1.1.0 not listed): ${allRuntimes.map(runtime => `\n${runtime.description}`).join("")}`; - } - [...Failures.keys()].forEach(otherRuntimeIndex => { - let comparison; - let otherRuntime; - if (otherRuntimeIndex === UNKNOWN_RUNTIME) { - comparison = 1; - otherRuntime = { - description: `Older unknown runtime` - }; - } else { - comparison = compareRuntimes(currentRuntimeIndex, otherRuntimeIndex); - otherRuntime = allRuntimes[otherRuntimeIndex]; - } - let compareWord; - if (comparison > 0) { - compareWord = "an older"; - } else if (comparison < 0) { - compareWord = "a newer"; - } else { - compareWord = "the same"; - } - message = `${message}\n\n"${currentRuntime.description}" failed to define ${Failures.get(otherRuntimeIndex).size} tag(s) as they were defined by a runtime of ${compareWord} version "${otherRuntime.description}": ${[...Failures.get(otherRuntimeIndex)].sort().join(", ")}.`; - if (comparison > 0) { - message = `${message}\nWARNING! If your code uses features of the above web components, unavailable in ${otherRuntime.description}, it might not work as expected!`; - } else { - message = `${message}\nSince the above web components were defined by the same or newer version runtime, they should be compatible with your code.`; - } - }); - message = `${message}\n\nTo prevent other runtimes from defining tags that you use, consider using scoping or have third-party libraries use scoping: https://github.com/SAP/ui5-webcomponents/blob/main/docs/2-advanced/03-scoping.md.`; - console.warn(message); - }; + const u$c=()=>{const t=document.createElement("meta");return t.setAttribute("name","ui5-shared-resources"),t.setAttribute("content",""),t},l$h=()=>typeof document>"u"?null:o$i('meta[name="ui5-shared-resources"]',document.head,u$c),m$c=(t,o)=>{const r=t.split(".");let e=l$h();if(!e)return o;for(let n=0;n { - rtlAwareSet.add(klass); - }; - const isRtlAware = (klass) => { - return rtlAwareSet.has(klass); - }; + const e$e={version:"2.5.0",major:2,minor:5,patch:0,suffix:"",isNext:!1,buildTime:1733409507}; - const registeredElements = new Set(); - const eventProvider$4 = new EventProvider(); - const invalidatedWebComponents = new RenderQueue(); // Queue for invalidated web components - let renderTaskPromise, renderTaskPromiseResolve; - let mutationObserverTimer; - let queuePromise; - /** - * Schedules a render task (if not already scheduled) to render the component - * - * @param webComponent - * @returns {Promise} - */ - const renderDeferred = async (webComponent) => { - // Enqueue the web component - invalidatedWebComponents.add(webComponent); - // Schedule a rendering task - await scheduleRenderTask(); - }; - /** - * Renders a component synchronously and adds it to the registry of rendered components - * - * @param webComponent - */ - const renderImmediately = (webComponent) => { - eventProvider$4.fireEvent("beforeComponentRender", webComponent); - registeredElements.add(webComponent); - webComponent._render(); - }; - /** - * Cancels the rendering of a component, if awaiting to be rendered, and removes it from the registry of rendered components - * - * @param webComponent - */ - const cancelRender = (webComponent) => { - invalidatedWebComponents.remove(webComponent); - registeredElements.delete(webComponent); - }; - /** - * Schedules a rendering task, if not scheduled already - */ - const scheduleRenderTask = async () => { - if (!queuePromise) { - queuePromise = new Promise(resolve => { - window.requestAnimationFrame(() => { - // Render all components in the queue - // console.log(`--------------------RENDER TASK START------------------------------`); // eslint-disable-line - invalidatedWebComponents.process(renderImmediately); - // console.log(`--------------------RENDER TASK END------------------------------`); // eslint-disable-line - // Resolve the promise so that callers of renderDeferred can continue - queuePromise = null; - resolve(); - // Wait for Mutation observer before the render task is considered finished - if (!mutationObserverTimer) { - mutationObserverTimer = setTimeout(() => { - mutationObserverTimer = undefined; - if (invalidatedWebComponents.isEmpty()) { - _resolveTaskPromise(); - } - }, 200); - } - }); - }); - } - await queuePromise; - }; - /** - * return a promise that will be resolved once all invalidated web components are rendered - */ - const whenDOMUpdated = () => { - if (renderTaskPromise) { - return renderTaskPromise; - } - renderTaskPromise = new Promise(resolve => { - renderTaskPromiseResolve = resolve; - window.requestAnimationFrame(() => { - if (invalidatedWebComponents.isEmpty()) { - renderTaskPromise = undefined; - resolve(); - } - }); - }); - return renderTaskPromise; - }; - const whenAllCustomElementsAreDefined = () => { - const definedPromises = getAllRegisteredTags().map(tag => customElements.whenDefined(tag)); - return Promise.all(definedPromises); - }; - const renderFinished = async () => { - await whenAllCustomElementsAreDefined(); - await whenDOMUpdated(); - }; - const _resolveTaskPromise = () => { - if (!invalidatedWebComponents.isEmpty()) { - // More updates are pending. Resolve will be called again - return; - } - if (renderTaskPromiseResolve) { - renderTaskPromiseResolve(); - renderTaskPromiseResolve = undefined; - renderTaskPromise = undefined; - } - }; - /** - * Re-renders all UI5 Elements on the page, with the option to specify filters to rerender only some components. - * - * Usage: - * reRenderAllUI5Elements() -> re-renders all components - * reRenderAllUI5Elements({tag: "ui5-button"}) -> re-renders only instances of ui5-button - * reRenderAllUI5Elements({rtlAware: true}) -> re-renders only rtlAware components - * reRenderAllUI5Elements({languageAware: true}) -> re-renders only languageAware components - * reRenderAllUI5Elements({themeAware: true}) -> re-renders only themeAware components - * reRenderAllUI5Elements({rtlAware: true, languageAware: true}) -> re-renders components that are rtlAware or languageAware - * etc... - * - * @public - * @param {object|undefined} filters - Object with keys that can be "rtlAware" or "languageAware" - * @returns {Promise} - */ - const reRenderAllUI5Elements = async (filters) => { - registeredElements.forEach((element) => { - const ctor = element.constructor; - const tag = ctor.getMetadata().getTag(); - const rtlAware = isRtlAware(ctor); - const languageAware = ctor.getMetadata().isLanguageAware(); - const themeAware = ctor.getMetadata().isThemeAware(); - if (!filters || (filters.tag === tag) || (filters.rtlAware && rtlAware) || (filters.languageAware && languageAware) || (filters.themeAware && themeAware)) { - renderDeferred(element); - } - }); - await renderFinished(); - }; + let o$h,t$i={include:[/^ui5-/],exclude:[]};const s$l=new Map,c$h=()=>o$h,m$b=()=>t$i,i$i=e=>{if(!s$l.has(e)){const r=t$i.include.some(n=>e.match(n))&&!t$i.exclude.some(n=>e.match(n));s$l.set(e,r);}return s$l.get(e)},p$8=e=>{if(i$i(e))return c$h()}; - const isSSR$2 = typeof document === "undefined"; - const getStyleId = (name, value) => { - return value ? `${name}|${value}` : name; - }; - const shouldUpdate = (runtimeIndex) => { - if (runtimeIndex === undefined) { - return true; - } - return compareRuntimes(getCurrentRuntimeIndex(), parseInt(runtimeIndex)) === 1; // 1 means the current is newer, 0 means the same, -1 means the resource's runtime is newer - }; - const createStyle = (data, name, value = "", theme) => { - const content = typeof data === "string" ? data : data.content; - const currentRuntimeIndex = getCurrentRuntimeIndex(); - const stylesheet = new CSSStyleSheet(); - stylesheet.replaceSync(content); - stylesheet._ui5StyleId = getStyleId(name, value); // set an id so that we can find the style later - if (theme) { - stylesheet._ui5RuntimeIndex = currentRuntimeIndex; - stylesheet._ui5Theme = theme; - } - document.adoptedStyleSheets = [...document.adoptedStyleSheets, stylesheet]; - }; - const updateStyle = (data, name, value = "", theme) => { - const content = typeof data === "string" ? data : data.content; - const currentRuntimeIndex = getCurrentRuntimeIndex(); - const stylesheet = document.adoptedStyleSheets.find(sh => sh._ui5StyleId === getStyleId(name, value)); - if (!stylesheet) { - return; - } - if (!theme) { - stylesheet.replaceSync(content || ""); - } - else { - const stylesheetRuntimeIndex = stylesheet._ui5RuntimeIndex; - const stylesheetTheme = stylesheet._ui5Theme; - if (stylesheetTheme !== theme || shouldUpdate(stylesheetRuntimeIndex)) { - stylesheet.replaceSync(content || ""); - stylesheet._ui5RuntimeIndex = String(currentRuntimeIndex); - stylesheet._ui5Theme = theme; - } - } - }; - const hasStyle = (name, value = "") => { - if (isSSR$2) { - return true; - } - return !!document.adoptedStyleSheets.find(sh => sh._ui5StyleId === getStyleId(name, value)); - }; - const removeStyle = (name, value = "") => { - document.adoptedStyleSheets = document.adoptedStyleSheets.filter(sh => sh._ui5StyleId !== getStyleId(name, value)); - }; - const createOrUpdateStyle = (data, name, value = "", theme) => { - if (hasStyle(name, value)) { - updateStyle(data, name, value, theme); - } - else { - createStyle(data, name, value, theme); - } - }; - const mergeStyles = (style1, style2) => { - if (style1 === undefined) { - return style2; - } - if (style2 === undefined) { - return style1; - } - const style2Content = typeof style2 === "string" ? style2 : style2.content; - if (typeof style1 === "string") { - return `${style1} ${style2Content}`; - } - return { - content: `${style1.content} ${style2Content}`, - packageName: style1.packageName, - fileName: style1.fileName, - }; - }; + let i$h,s$k="";const u$b=new Map,r$i=m$c("Runtimes",[]),x$1=()=>{if(i$h===void 0){i$h=r$i.length;const e=e$e;r$i.push({...e,get scopingSuffix(){return c$h()},get registeredTags(){return $$2()},get scopingRules(){return m$b()},alias:s$k,description:`Runtime ${i$h} - ver ${e.version}${""}`});}},I$5=()=>i$h,b$5=(e,m)=>{const o=`${e},${m}`;if(u$b.has(o))return u$b.get(o);const t=r$i[e],n=r$i[m];if(!t||!n)throw new Error("Invalid runtime index supplied");if(t.isNext||n.isNext)return t.buildTime-n.buildTime;const c=t.major-n.major;if(c)return c;const a=t.minor-n.minor;if(a)return a;const f=t.patch-n.patch;if(f)return f;const l=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}).compare(t.suffix,n.suffix);return u$b.set(o,l),l},$$3=()=>r$i; - const eventProvider$3 = new EventProvider(); - const THEME_REGISTERED = "themeRegistered"; - const attachThemeRegistered = (listener) => { - eventProvider$3.attachEvent(THEME_REGISTERED, listener); - }; - const fireThemeRegistered = (theme) => { - return eventProvider$3.fireEvent(THEME_REGISTERED, theme); - }; + const m$a = m$c("Tags", new Map()), d$b = new Set(); + let s$j = new Map(), c$g; + const g$6 = -1, h$5 = e => { + (d$b.add(e), m$a.set(e, I$5())); + }, w$5 = e => d$b.has(e), $$2 = () => [...d$b.values()], y$7 = e => { + let n = m$a.get(e); + (n === void 0 && (n = g$6), s$j.has(n) || s$j.set(n, new Set()), s$j.get(n).add(e), c$g || (c$g = setTimeout(() => { + (R$3(), s$j = new Map(), c$g = void 0); + }, 1000))); + }, R$3 = () => { + const e = $$3(), n = I$5(), l = e[n]; + let t = "Multiple UI5 Web Components instances detected."; + (e.length > 1 && (t = `${t} +Loading order (versions before 1.1.0 not listed): ${e.map(i => ` +${i.description}`).join("")}`), [...s$j.keys()].forEach(i => { + let o, r; + i === g$6 ? (o = 1, r = { + description: "Older unknown runtime" + }) : (o = b$5(n, i), r = e[i]); + let a; + (o > 0 ? a = "an older" : o < 0 ? a = "a newer" : a = "the same", t = `${t} - const themeStyles = new Map(); - const loaders$3 = new Map(); - const customLoaders = new Map(); - const registeredPackages = new Set(); - const registeredThemes = new Set(); - const registerThemePropertiesLoader = (packageName, themeName, loader) => { - loaders$3.set(`${packageName}/${themeName}`, loader); - registeredPackages.add(packageName); - registeredThemes.add(themeName); - fireThemeRegistered(themeName); - }; - const getThemeProperties = async (packageName, themeName, externalThemeName) => { - const cacheKey = `${packageName}_${themeName}_${externalThemeName || ""}`; - const cachedStyleData = themeStyles.get(cacheKey); - if (cachedStyleData !== undefined) { // it's valid for style to be an empty string - return cachedStyleData; - } - if (!registeredThemes.has(themeName)) { - const regThemesStr = [...registeredThemes.values()].join(", "); - console.warn(`You have requested a non-registered theme ${themeName} - falling back to ${DEFAULT_THEME}. Registered themes are: ${regThemesStr}`); /* eslint-disable-line */ - return _getThemeProperties(packageName, DEFAULT_THEME); - } - const [style, customStyle] = await Promise.all([ - _getThemeProperties(packageName, themeName), - externalThemeName ? _getThemeProperties(packageName, externalThemeName, true) : undefined, - ]); - const styleData = mergeStyles(style, customStyle); - if (styleData) { - themeStyles.set(cacheKey, styleData); - } - return styleData; - }; - const _getThemeProperties = async (packageName, themeName, forCustomTheme = false) => { - const loadersMap = forCustomTheme ? customLoaders : loaders$3; - const loader = loadersMap.get(`${packageName}/${themeName}`); - if (!loader) { - // no themes for package - if (!forCustomTheme) { - console.error(`Theme [${themeName}] not registered for package [${packageName}]`); /* eslint-disable-line */ - } - return; - } - let data; - try { - data = await loader(themeName); - } - catch (error) { - const e = error; - console.error(packageName, e.message); /* eslint-disable-line */ - return; - } - const themeProps = data._ || data; // Refactor: remove _ everywhere - return themeProps; - }; - const getRegisteredPackages = () => { - return registeredPackages; - }; - const isThemeRegistered = (theme) => { - return registeredThemes.has(theme); - }; - - const warnings = new Set(); - const getThemeMetadata = () => { - // Check if the class was already applied, most commonly to the link/style tag with the CSS Variables - let el = document.querySelector(".sapThemeMetaData-Base-baseLib") || document.querySelector(".sapThemeMetaData-UI5-sap-ui-core"); - if (el) { - return getComputedStyle(el).backgroundImage; - } - el = document.createElement("span"); - el.style.display = "none"; - // Try with sapThemeMetaData-Base-baseLib first - el.classList.add("sapThemeMetaData-Base-baseLib"); - document.body.appendChild(el); - let metadata = getComputedStyle(el).backgroundImage; - // Try with sapThemeMetaData-UI5-sap-ui-core only if the previous selector was not found - if (metadata === "none") { - el.classList.add("sapThemeMetaData-UI5-sap-ui-core"); - metadata = getComputedStyle(el).backgroundImage; - } - document.body.removeChild(el); - return metadata; - }; - const parseThemeMetadata = (metadataString) => { - const params = /\(["']?data:text\/plain;utf-8,(.*?)['"]?\)$/i.exec(metadataString); - if (params && params.length >= 2) { - let paramsString = params[1]; - paramsString = paramsString.replace(/\\"/g, `"`); - if (paramsString.charAt(0) !== "{" && paramsString.charAt(paramsString.length - 1) !== "}") { - try { - paramsString = decodeURIComponent(paramsString); - } - catch (ex) { - if (!warnings.has("decode")) { - console.warn("Malformed theme metadata string, unable to decodeURIComponent"); // eslint-disable-line - warnings.add("decode"); - } - return; - } - } - try { - return JSON.parse(paramsString); - } - catch (ex) { - if (!warnings.has("parse")) { - console.warn("Malformed theme metadata string, unable to parse JSON"); // eslint-disable-line - warnings.add("parse"); - } - } - } - }; - const processThemeMetadata = (metadata) => { - let themeName; - let baseThemeName; - try { - themeName = metadata.Path.match(/\.([^.]+)\.css_variables$/)[1]; - baseThemeName = metadata.Extends[0]; - } - catch (ex) { - if (!warnings.has("object")) { - console.warn("Malformed theme metadata Object", metadata); // eslint-disable-line - warnings.add("object"); - } - return; - } - return { - themeName, - baseThemeName, - }; - }; - const getThemeDesignerTheme = () => { - const metadataString = getThemeMetadata(); - if (!metadataString || metadataString === "none") { - return; - } - const metadata = parseThemeMetadata(metadataString); - if (metadata) { - return processThemeMetadata(metadata); - } - }; - - const eventProvider$2 = new EventProvider(); - const THEME_LOADED = "themeLoaded"; - const fireThemeLoaded = (theme) => { - return eventProvider$2.fireEvent(THEME_LOADED, theme); - }; - - /** - * Creates a `` tag in the `` tag - * @param href - the CSS - * @param attributes - optional attributes to add to the tag - */ - const createLinkInHead = (href, attributes) => { - const link = document.createElement("link"); - link.type = "text/css"; - link.rel = "stylesheet"; - if (attributes) { - Object.entries(attributes).forEach(pair => link.setAttribute(...pair)); - } - link.href = href; - document.head.appendChild(link); - return new Promise(resolve => { - link.addEventListener("load", resolve); - link.addEventListener("error", resolve); // intended - }); - }; - - let currThemeRoot; - attachConfigurationReset(() => { - currThemeRoot = undefined; - }); - /** - * Returns the current theme root. - * - * @public - * @since 1.14.0 - * @returns { string } the current theme root - */ - const getThemeRoot = () => { - if (currThemeRoot === undefined) { - currThemeRoot = getThemeRoot$1(); - } - return currThemeRoot; - }; - const formatThemeLink = (theme) => { - return `${getThemeRoot()}Base/baseLib/${theme}/css_variables.css`; // theme root is always set at this point. - }; - const attachCustomThemeStylesToHead = async (theme) => { - const link = document.querySelector(`[sap-ui-webcomponents-theme="${theme}"]`); - if (link) { - document.head.removeChild(link); - } - await createLinkInHead(formatThemeLink(theme), { "sap-ui-webcomponents-theme": theme }); - }; - - const BASE_THEME_PACKAGE = "@ui5/webcomponents-theming"; - const isThemeBaseRegistered = () => { - const registeredPackages = getRegisteredPackages(); - return registeredPackages.has(BASE_THEME_PACKAGE); - }; - const loadThemeBase = async (theme) => { - if (!isThemeBaseRegistered()) { - return; - } - const cssData = await getThemeProperties(BASE_THEME_PACKAGE, theme); - if (cssData) { - createOrUpdateStyle(cssData, "data-ui5-theme-properties", BASE_THEME_PACKAGE, theme); - } - }; - const deleteThemeBase = () => { - removeStyle("data-ui5-theme-properties", BASE_THEME_PACKAGE); - }; - const loadComponentPackages = async (theme, externalThemeName) => { - const registeredPackages = getRegisteredPackages(); - const packagesStylesPromises = [...registeredPackages].map(async (packageName) => { - if (packageName === BASE_THEME_PACKAGE) { - return; - } - const cssData = await getThemeProperties(packageName, theme, externalThemeName); - if (cssData) { - createOrUpdateStyle(cssData, `data-ui5-component-properties-${getCurrentRuntimeIndex()}`, packageName); - } - }); - return Promise.all(packagesStylesPromises); - }; - const detectExternalTheme = async (theme) => { - // If theme designer theme is detected, use this - const extTheme = getThemeDesignerTheme(); - if (extTheme) { - return extTheme; - } - // If OpenUI5Support is enabled, try to find out if it loaded variables - const openUI5Support = getFeature("OpenUI5Support"); - if (openUI5Support && openUI5Support.isOpenUI5Detected()) { - const varsLoaded = openUI5Support.cssVariablesLoaded(); - if (varsLoaded) { - return { - themeName: openUI5Support.getConfigurationSettingsObject()?.theme, // just themeName - baseThemeName: "", // baseThemeName is only relevant for custom themes - }; - } - } - else if (getThemeRoot()) { - await attachCustomThemeStylesToHead(theme); - return getThemeDesignerTheme(); - } - }; - const applyTheme = async (theme) => { - const extTheme = await detectExternalTheme(theme); - // Only load theme_base properties if there is no externally loaded theme, or there is, but it is not being loaded - if (!extTheme || theme !== extTheme.themeName) { - await loadThemeBase(theme); - } - else { - deleteThemeBase(); - } - // Always load component packages properties. For non-registered themes, try with the base theme, if any - const packagesTheme = isThemeRegistered(theme) ? theme : extTheme && extTheme.baseThemeName; - await loadComponentPackages(packagesTheme || DEFAULT_THEME, extTheme && extTheme.themeName === theme ? theme : undefined); - fireThemeLoaded(theme); - }; - - const whenDOMReady = () => { - return new Promise(resolve => { - if (document.body) { - resolve(); - } - else { - document.addEventListener("DOMContentLoaded", () => { - resolve(); - }); - } - }); - }; - - const styleData$7 = { - packageName: "@ui5/webcomponents-base", - fileName: "FontFace.css", - content: `@font-face{font-family:"72";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular.woff2?ui5-webcomponents) format("woff2"),local("72");unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular-full.woff2?ui5-webcomponents) format("woff2"),local('72-full')}@font-face{font-family:"72";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Bold';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Boldfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Light';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light.woff2?ui5-webcomponents) format("woff2"),local('72-Light');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Lightfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72Mono';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular.woff2?ui5-webcomponents) format('woff2'),local('72Mono');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Monofull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:'72Mono-Bold';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold.woff2?ui5-webcomponents) format('woff2'),local('72Mono-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Mono-Boldfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72Black";font-style:bold;font-weight:900;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black.woff2?ui5-webcomponents) format("woff2"),local('72Black');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Blackfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72-SemiboldDuplex";src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-SemiboldDuplex.woff2?ui5-webcomponents) format("woff2"),local('72-SemiboldDuplex');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}`, - }; - - const styleData$6 = { - packageName: "@ui5/webcomponents-base", - fileName: "OverrideFontFace.css", - content: `@font-face{font-family:'72override';unicode-range:U+0102-0103,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EB7,U+1EB8-1EC7,U+1EC8-1ECB,U+1ECC-1EE3,U+1EE4-1EF1,U+1EF4-1EF7;src:local('Arial'),local('Helvetica'),local('sans-serif')}`, - }; - - let defaultFontLoading; - attachConfigurationReset(() => { - defaultFontLoading = undefined; - }); - /** - * Returns if the "defaultFontLoading" configuration is set. - * @public - * @returns { boolean } - */ - const getDefaultFontLoading = () => { - if (defaultFontLoading === undefined) { - defaultFontLoading = getDefaultFontLoading$1(); - } - return defaultFontLoading; - }; - - const insertFontFace = () => { - const openUI5Support = getFeature("OpenUI5Support"); - // Only set the main font if there is no OpenUI5 support, or there is, but OpenUI5 is not loaded - if ((!openUI5Support || !openUI5Support.isOpenUI5Detected())) { - insertMainFontFace(); - } - // Always set the override font - OpenUI5 in CSS Vars mode does not set it, unlike the main font - insertOverrideFontFace(); - }; - const insertMainFontFace = () => { - const hasFontStyles = document.querySelector("head>style[data-ui5-font-face]"); - if (!getDefaultFontLoading() || hasFontStyles) { - return; - } - if (!hasStyle("data-ui5-font-face")) { - createStyle(styleData$7, "data-ui5-font-face"); - } - }; - const insertOverrideFontFace = () => { - if (!hasStyle("data-ui5-font-face-override")) { - createStyle(styleData$6, "data-ui5-font-face-override"); - } - }; - - const styleData$5 = { - packageName: "@ui5/webcomponents-base", - fileName: "SystemCSSVars.css", - content: `:root{--_ui5_content_density:cozy}.sapUiSizeCompact,.ui5-content-density-compact,[data-ui5-compact-size]{--_ui5_content_density:compact}`, - }; - - const insertSystemCSSVars = () => { - if (!hasStyle("data-ui5-system-css-vars")) { - createStyle(styleData$5, "data-ui5-system-css-vars"); - } - }; - - const isSSR$1 = typeof document === "undefined"; - const internals = { - get userAgent() { - if (isSSR$1) { - return ""; - } - return navigator.userAgent; - }, - get touch() { - if (isSSR$1) { - return false; - } - return "ontouchstart" in window || navigator.maxTouchPoints > 0; - }, - get chrome() { - if (isSSR$1) { - return false; - } - return /(Chrome|CriOS)/.test(internals.userAgent); - }, - get firefox() { - if (isSSR$1) { - return false; - } - return /Firefox/.test(internals.userAgent); - }, - get safari() { - if (isSSR$1) { - return false; - } - return !internals.chrome && /(Version|PhantomJS)\/(\d+\.\d+).*Safari/.test(internals.userAgent); - }, - get webkit() { - if (isSSR$1) { - return false; - } - return /webkit/.test(internals.userAgent); - }, - get windows() { - if (isSSR$1) { - return false; - } - return navigator.platform.indexOf("Win") !== -1; - }, - get macOS() { - if (isSSR$1) { - return false; - } - return !!navigator.userAgent.match(/Macintosh|Mac OS X/i); - }, - get iOS() { - if (isSSR$1) { - return false; - } - return !!(navigator.platform.match(/iPhone|iPad|iPod/)) || !!(internals.userAgent.match(/Mac/) && "ontouchend" in document); - }, - get android() { - if (isSSR$1) { - return false; - } - return !internals.windows && /Android/.test(internals.userAgent); - }, - get androidPhone() { - if (isSSR$1) { - return false; - } - return internals.android && /(?=android)(?=.*mobile)/i.test(internals.userAgent); - }, - get ipad() { - if (isSSR$1) { - return false; - } - // With iOS 13 the string 'iPad' was removed from the user agent string through a browser setting, which is applied on all sites by default: - // "Request Desktop Website -> All websites" (for more infos see: https://forums.developer.apple.com/thread/119186). - // Therefore the OS is detected as MACINTOSH instead of iOS and the device is a tablet if the Device.support.touch is true. - return /ipad/i.test(internals.userAgent) || (/Macintosh/i.test(internals.userAgent) && "ontouchend" in document); - }, - _isPhone() { - detectTablet(); - return internals.touch && !tablet; - }, - }; - let windowsVersion; - let webkitVersion; - let tablet; - const isWindows8OrAbove = () => { - if (isSSR$1) { - return false; - } - if (!internals.windows) { - return false; - } - if (windowsVersion === undefined) { - const matches = internals.userAgent.match(/Windows NT (\d+).(\d)/); - windowsVersion = matches ? parseFloat(matches[1]) : 0; - } - return windowsVersion >= 8; - }; - const isWebkit537OrAbove = () => { - if (isSSR$1) { - return false; - } - if (!internals.webkit) { - return false; - } - if (webkitVersion === undefined) { - const matches = internals.userAgent.match(/(webkit)[ /]([\w.]+)/); - webkitVersion = matches ? parseFloat(matches[1]) : 0; - } - return webkitVersion >= 537.10; - }; - const detectTablet = () => { - if (isSSR$1) { - return false; - } - if (tablet !== undefined) { - return; - } - if (internals.ipad) { - tablet = true; - return; - } - if (internals.touch) { - if (isWindows8OrAbove()) { - tablet = true; - return; - } - if (internals.chrome && internals.android) { - tablet = !/Mobile Safari\/[.0-9]+/.test(internals.userAgent); - return; - } - let densityFactor = window.devicePixelRatio ? window.devicePixelRatio : 1; // may be undefined in Windows Phone devices - if (internals.android && isWebkit537OrAbove()) { - densityFactor = 1; - } - tablet = (Math.min(window.screen.width / densityFactor, window.screen.height / densityFactor) >= 600); - return; - } - tablet = internals.userAgent.indexOf("Touch") !== -1 || (internals.android && !internals.androidPhone); - }; - const isSafari = () => internals.safari; - const isTablet = () => { - detectTablet(); - return (internals.touch || isWindows8OrAbove()) && tablet; - }; - const isPhone = () => { - return internals._isPhone(); - }; - const isDesktop = () => { - if (isSSR$1) { - return false; - } - return (!isTablet() && !isPhone()) || isWindows8OrAbove(); - }; - const isIOS = () => { - return internals.iOS; - }; - - let listenerAttached = false; - const fixSafariActiveState = () => { - if (isSafari() && isIOS() && !listenerAttached) { - // Safari on iOS does not use the :active state unless there is a touchstart event handler on the element - document.body.addEventListener("touchstart", () => { }); - listenerAttached = true; - } - }; - - let booted = false; - let bootPromise; - const eventProvider$1 = new EventProvider(); - const boot = async () => { - if (bootPromise !== undefined) { - return bootPromise; - } - const bootExecutor = async (resolve) => { - registerCurrentRuntime(); - if (typeof document === "undefined") { - resolve(); - return; - } - attachThemeRegistered(onThemeRegistered); - const openUI5Support = getFeature("OpenUI5Support"); - const isOpenUI5Loaded = openUI5Support ? openUI5Support.isOpenUI5Detected() : false; - const f6Navigation = getFeature("F6Navigation"); - if (openUI5Support) { - await openUI5Support.init(); - } - if (f6Navigation && !isOpenUI5Loaded) { - f6Navigation.init(); - } - await whenDOMReady(); - await applyTheme(getTheme()); - openUI5Support && openUI5Support.attachListeners(); - insertFontFace(); - insertSystemCSSVars(); - fixSafariActiveState(); - resolve(); - booted = true; - eventProvider$1.fireEvent("boot"); - }; - bootPromise = new Promise(bootExecutor); - return bootPromise; - }; - /** - * Callback, executed after theme properties registration - * to apply the newly registered theme. - * @private - * @param { string } theme - */ - const onThemeRegistered = (theme) => { - if (booted && theme === getTheme()) { // getTheme should only be called if "booted" is true - applyTheme(getTheme()); - } - }; +"${l.description}" failed to define ${s$j.get(i).size} tag(s) as they were defined by a runtime of ${a} version "${r.description}": ${[...s$j.get(i)].sort().join(", ")}.`, o > 0 ? t = `${t} +WARNING! If your code uses features of the above web components, unavailable in ${r.description}, it might not work as expected!` : t = `${t} +Since the above web components were defined by the same or newer version runtime, they should be compatible with your code.`); + }), t = `${t} - let curTheme; - attachConfigurationReset(() => { - curTheme = undefined; - }); - /** - * Returns the current theme. - * @public - * @returns {string} the current theme name - */ - const getTheme = () => { - if (curTheme === undefined) { - curTheme = getTheme$1(); - } - return curTheme; - }; - /** - * Returns if the currently set theme is part of legacy theme families ("sap_fiori_3"). - * **Note**: in addition, the method checks the base theme of a custom theme, built via the ThemeDesigner. - * - * @private - * @returns { boolean } - */ - const isLegacyThemeFamily = () => { - const currentTheme = getTheme(); - if (!isKnownTheme(currentTheme)) { - return !getThemeDesignerTheme()?.baseThemeName?.startsWith("sap_horizon"); - } - return !currentTheme.startsWith("sap_horizon"); - }; - const isKnownTheme = (theme) => SUPPORTED_THEMES.includes(theme); - - var RegisteredIconCollection; - (function (RegisteredIconCollection) { - RegisteredIconCollection["SAPIconsV4"] = "SAP-icons-v4"; - RegisteredIconCollection["SAPIconsV5"] = "SAP-icons-v5"; - RegisteredIconCollection["SAPIconsTNTV2"] = "tnt-v2"; - RegisteredIconCollection["SAPIconsTNTV3"] = "tnt-v3"; - RegisteredIconCollection["SAPBSIconsV1"] = "business-suite-v1"; - RegisteredIconCollection["SAPBSIconsV2"] = "business-suite-v2"; - })(RegisteredIconCollection || (RegisteredIconCollection = {})); - const iconCollections = new Map(); - iconCollections.set("SAP-icons", { - "legacy": RegisteredIconCollection.SAPIconsV4, - "sap_horizon": RegisteredIconCollection.SAPIconsV5, - }); - iconCollections.set("tnt", { - "legacy": RegisteredIconCollection.SAPIconsTNTV2, - "sap_horizon": RegisteredIconCollection.SAPIconsTNTV3, - }); - iconCollections.set("business-suite", { - "legacy": RegisteredIconCollection.SAPBSIconsV1, - "sap_horizon": RegisteredIconCollection.SAPBSIconsV2, - }); - /** - * Registers collection version per theme. - * **For exmaple:** registerIconCollectionForTheme("my-custom-icons", {"sap_horizon": "my-custom-icons-v5"}) - * @param { string } collectionName - * @param { ThemeToCollectionMap } themeCollectionMap - */ - const registerIconCollectionForTheme = (collectionName, themeCollectionMap) => { - if (iconCollections.has(collectionName)) { - iconCollections.set(collectionName, { ...themeCollectionMap, ...iconCollections.get(collectionName) }); - return; - } - iconCollections.set(collectionName, themeCollectionMap); - }; - const getIconCollectionForTheme = (collectionName) => { - const themeFamily = isLegacyThemeFamily() ? "legacy" : "sap_horizon"; - return iconCollections.has(collectionName) ? iconCollections.get(collectionName)[themeFamily] : collectionName; - }; +To prevent other runtimes from defining tags that you use, consider using scoping or have third-party libraries use scoping: https://github.com/SAP/ui5-webcomponents/blob/main/docs/2-advanced/03-scoping.md.`, console.warn(t)); + }; - /** - * Supported icon collection aliases. - * - * Users might specify a collection, using both the key and the value in the following key-value pairs, - * e.g the following pairs are completely exchangeable: - * - * - "SAP-icons/accept" and "SAP-icons-v4/accept" - * - "horizon/accept" and "SAP-icons-v5/accept" - * - "SAP-icons-TNT/actor" and "tnt/actor" - * - "BusinessSuiteInAppSymbols/3d" and "business-suite/3d" - */ - var IconCollectionsAlias; - (function (IconCollectionsAlias) { - IconCollectionsAlias["SAP-icons"] = "SAP-icons-v4"; - IconCollectionsAlias["horizon"] = "SAP-icons-v5"; - IconCollectionsAlias["SAP-icons-TNT"] = "tnt"; - IconCollectionsAlias["BusinessSuiteInAppSymbols"] = "business-suite"; - })(IconCollectionsAlias || (IconCollectionsAlias = {})); - /** - * Returns the collection name for a given alias: - * - * - "SAP-icons-TNT"resolves to "tnt" - * - "BusinessSuiteInAppSymbols" resolves to "business-suite" - * - "horizon" resolves to "SAP-icons-v5" - * - * @param { string } collectionName - * @return { string } the normalized collection name - */ - const getIconCollectionByAlias = (collectionName) => { - if (IconCollectionsAlias[collectionName]) { - return IconCollectionsAlias[collectionName]; - } - return collectionName; - }; + const t$h=new Set,n$i=e=>{t$h.add(e);},r$h=e=>t$h.has(e); - /** - * Returns the effective theme dependant icon collection: - * - * - "no collection" resolves to "SAP-icons-v4" in "Quartz" and to "SAP-icons-v5" in "Horizon" - * - "tnt" (and its alias "SAP-icons-TNT") resolves to "tnt-v2" in "Quartz" and resolves to "tnt-v3" in "Horizon" - * - "business-suite" (and its alias "BusinessSuiteInAppSymbols") resolves to "business-suite-v1" in "Quartz" and resolves to "business-suite-v2" in "Horizon" - * - * @param { IconCollection } collectionName - * @returns { IconCollection } the effective collection name - */ - const getEffectiveIconCollection = (collectionName) => { - const defaultIconCollection = getDefaultIconCollection(getTheme()); - // no collection + default collection, configured via setDefaultIconCollection - return the configured icon collection. - if (!collectionName && defaultIconCollection) { - return getIconCollectionByAlias(defaultIconCollection); - } - // no collection - return "SAP-icons-v4" or "SAP-icons-v5". - if (!collectionName) { - return getIconCollectionForTheme("SAP-icons"); - } - // has collection - return "SAP-icons-v4", "SAP-icons-v5", "tnt-v1", "tnt-v2", "business-suite-v1", "business-suite-v2", or custom ones. - return getIconCollectionForTheme(collectionName); - }; + const s$i=new Set,d$a=new i$n,n$h=new l$i;let t$g,a$b,m$9,i$g;const l$g=async e=>{n$h.add(e),await P$3();},c$f=e=>{d$a.fireEvent("beforeComponentRender",e),s$i.add(e),e._render();},h$4=e=>{n$h.remove(e),s$i.delete(e);},P$3=async()=>{i$g||(i$g=new Promise(e=>{window.requestAnimationFrame(()=>{n$h.process(c$f),i$g=null,e(),m$9||(m$9=setTimeout(()=>{m$9=void 0,n$h.isEmpty()&&U$1();},200));});})),await i$g;},y$6=()=>t$g||(t$g=new Promise(e=>{a$b=e,window.requestAnimationFrame(()=>{n$h.isEmpty()&&(t$g=void 0,e());});}),t$g),I$4=()=>{const e=$$2().map(r=>customElements.whenDefined(r));return Promise.all(e)},f$b=async()=>{await I$4(),await y$6();},U$1=()=>{n$h.isEmpty()&&a$b&&(a$b(),a$b=void 0,t$g=void 0);},C$2=async e=>{s$i.forEach(r=>{const o=r.constructor,u=o.getMetadata().getTag(),w=r$h(o),p=o.getMetadata().isLanguageAware(),E=o.getMetadata().isThemeAware();(!e||e.tag===u||e.rtlAware&&w||e.languageAware&&p||e.themeAware&&E)&&l$g(r);}),await f$b();}; - const eventProvider = new EventProvider(); - const LANG_CHANGE = "languageChange"; - const attachLanguageChange = (listener) => { - eventProvider.attachEvent(LANG_CHANGE, listener); - }; + const l$f=typeof document>"u",o$g=(e,t)=>t?`${e}|${t}`:e,f$a=e=>e===void 0?!0:b$5(I$5(),parseInt(e))===1,u$a=(e,t,n="",s)=>{const i=typeof e=="string"?e:e.content,c=I$5(),r=new CSSStyleSheet;r.replaceSync(i),r._ui5StyleId=o$g(t,n),s&&(r._ui5RuntimeIndex=c,r._ui5Theme=s),document.adoptedStyleSheets=[...document.adoptedStyleSheets,r];},y$5=(e,t,n="",s)=>{const i=typeof e=="string"?e:e.content,c=I$5(),r=document.adoptedStyleSheets.find(d=>d._ui5StyleId===o$g(t,n));if(r)if(!s)r.replaceSync(i||"");else {const d=r._ui5RuntimeIndex;(r._ui5Theme!==s||f$a(d))&&(r.replaceSync(i||""),r._ui5RuntimeIndex=String(c),r._ui5Theme=s);}},S$5=(e,t="")=>l$f?!0:!!document.adoptedStyleSheets.find(n=>n._ui5StyleId===o$g(e,t)),p$7=(e,t="")=>{document.adoptedStyleSheets=document.adoptedStyleSheets.filter(n=>n._ui5StyleId!==o$g(e,t));},m$8=(e,t,n="",s)=>{S$5(t,n)?y$5(e,t,n,s):u$a(e,t,n,s);},R$2=(e,t)=>{if(e===void 0)return t;if(t===void 0)return e;const n=typeof t=="string"?t:t.content;return typeof e=="string"?`${e} ${n}`:{content:`${e.content} ${n}`,packageName:e.packageName,fileName:e.fileName}}; - let curLanguage; - let fetchDefaultLanguage; - attachConfigurationReset(() => { - curLanguage = undefined; - fetchDefaultLanguage = undefined; - }); - /** - * Returns the currently configured language, or the browser language as a fallback. - * @public - * @returns {string} - */ - const getLanguage = () => { - if (curLanguage === undefined) { - curLanguage = getLanguage$1(); - } - return curLanguage; - }; - /** - * Returns if the default language, that is inlined, should be fetched over the network. - * @public - * @returns {boolean} - */ - const getFetchDefaultLanguage = () => { - if (fetchDefaultLanguage === undefined) { - fetchDefaultLanguage = getFetchDefaultLanguage$1(); - } - return fetchDefaultLanguage; - }; + const t$f=new i$n,r$g="themeRegistered",n$g=e=>{t$f.attachEvent(r$g,e);},s$h=e=>t$f.fireEvent(r$g,e); - // Fire these events even with noConflict: true - const excludeList = [ - "value-changed", - "click", - ]; - let noConflict; - attachConfigurationReset(() => { - noConflict = undefined; - }); - const shouldFireOriginalEvent = (eventName) => { - return excludeList.includes(eventName); - }; - const shouldNotFireOriginalEvent = (eventName) => { - const nc = getNoConflict(); - // return !(nc.events && nc.events.includes && nc.events.includes(eventName)); - return !(typeof nc !== "boolean" && nc.events && nc.events.includes && nc.events.includes(eventName)); - }; - /** - * Returns if the "noConflict" configuration is set. - * @public - * @returns { NoConflictData } - */ - const getNoConflict = () => { - if (noConflict === undefined) { - noConflict = getNoConflict$1(); - } - return noConflict; - }; - const skipOriginalEvent = (eventName) => { - const nc = getNoConflict(); - // Always fire these events - if (shouldFireOriginalEvent(eventName)) { - return false; - } - // Read from the configuration - if (nc === true) { - return true; - } - return !shouldNotFireOriginalEvent(eventName); - }; + const y$4=new Map,h$3=new Map,S$4=new Map,u$9=new Set,i$f=new Set,f$9=(e,t,r)=>{h$3.set(`${e}/${t}`,r),u$9.add(e),i$f.add(t),s$h(t);},P$2=async(e,t,r)=>{const a=`${e}_${t}_${r||""}`,s=y$4.get(a);if(s!==void 0)return s;if(!i$f.has(t)){const c=[...i$f.values()].join(", ");return console.warn(`You have requested a non-registered theme ${t} - falling back to ${e$g}. Registered themes are: ${c}`),g$5(e,e$g)}const[o,d]=await Promise.all([g$5(e,t),r?g$5(e,r,!0):void 0]),n=R$2(o,d);return n&&y$4.set(a,n),n},g$5=async(e,t,r=!1)=>{const s=(r?S$4:h$3).get(`${e}/${t}`);if(!s){r||console.error(`Theme [${t}] not registered for package [${e}]`);return}let o;try{o=await s(t);}catch(n){console.error(e,n.message);return}return o._||o},$$1=()=>u$9,D$2=e=>i$f.has(e); - /** - * Returns a custom element class decorator. - * - * @param { string | object } tagNameOrComponentSettings - * @returns { ClassDecorator } - */ - const customElement = (tagNameOrComponentSettings = {}) => { - return (target) => { - if (!Object.prototype.hasOwnProperty.call(target, "metadata")) { - target.metadata = {}; - } - if (typeof tagNameOrComponentSettings === "string") { - target.metadata.tag = tagNameOrComponentSettings; - return; - } - const { tag, languageAware, themeAware, cldr, fastNavigation, formAssociated, shadowRootOptions, features, } = tagNameOrComponentSettings; - target.metadata.tag = tag; - if (languageAware) { - target.metadata.languageAware = languageAware; - } - if (cldr) { - target.metadata.cldr = cldr; - } - if (features) { - target.metadata.features = features; - } - if (themeAware) { - target.metadata.themeAware = themeAware; - } - if (fastNavigation) { - target.metadata.fastNavigation = fastNavigation; - } - if (formAssociated) { - target.metadata.formAssociated = formAssociated; - } - if (shadowRootOptions) { - target.metadata.shadowRootOptions = shadowRootOptions; - } - ["renderer", "template", "styles", "dependencies"].forEach((customElementEntity) => { - const customElementEntityValue = tagNameOrComponentSettings[customElementEntity]; - customElementEntityValue && Object.defineProperty(target, customElementEntity, { - get: () => tagNameOrComponentSettings[customElementEntity], - }); - }); - }; - }; + const r$f=new Set,s$g=()=>{let e=document.querySelector(".sapThemeMetaData-Base-baseLib")||document.querySelector(".sapThemeMetaData-UI5-sap-ui-core");if(e)return getComputedStyle(e).backgroundImage;e=document.createElement("span"),e.style.display="none",e.classList.add("sapThemeMetaData-Base-baseLib"),document.body.appendChild(e);let t=getComputedStyle(e).backgroundImage;return t==="none"&&(e.classList.add("sapThemeMetaData-UI5-sap-ui-core"),t=getComputedStyle(e).backgroundImage),document.body.removeChild(e),t},o$f=e=>{const t=/\(["']?data:text\/plain;utf-8,(.*?)['"]?\)$/i.exec(e);if(t&&t.length>=2){let a=t[1];if(a=a.replace(/\\"/g,'"'),a.charAt(0)!=="{"&&a.charAt(a.length-1)!=="}")try{a=decodeURIComponent(a);}catch{r$f.has("decode")||(console.warn("Malformed theme metadata string, unable to decodeURIComponent"),r$f.add("decode"));return}try{return JSON.parse(a)}catch{r$f.has("parse")||(console.warn("Malformed theme metadata string, unable to parse JSON"),r$f.add("parse"));}}},d$9=e=>{let t,a;try{t=e.Path.match(/\.([^.]+)\.css_variables$/)[1],a=e.Extends[0];}catch{r$f.has("object")||(console.warn("Malformed theme metadata Object",e),r$f.add("object"));return}return {themeName:t,baseThemeName:a}},m$7=()=>{const e=s$g();if(!e||e==="none")return;const t=o$f(e);if(t)return d$9(t)}; - /** - * Returns a property decorator. - * - * @param { Property } propData - * @returns { PropertyDecorator } - */ - const property = (propData) => { - return (target, propertyKey) => { - const ctor = target.constructor; - if (!Object.prototype.hasOwnProperty.call(ctor, "metadata")) { - ctor.metadata = {}; - } - const metadata = ctor.metadata; - if (!metadata.properties) { - metadata.properties = {}; - } - const propsMetadata = metadata.properties; - if (!propsMetadata[propertyKey]) { - propsMetadata[propertyKey] = propData ?? {}; - } - }; - }; + const t$e=new i$n,d$8="themeLoaded",r$e=e=>t$e.fireEvent(d$8,e); - const KeyCodes = { - BACKSPACE: 8, - TAB: 9, - ENTER: 13, - SHIFT: 16, - CONTROL: 17, - ALT: 18, - BREAK: 19, - CAPS_LOCK: 20, - ESCAPE: 27, - SPACE: 32, - PAGE_UP: 33, - PAGE_DOWN: 34, - END: 35, - HOME: 36, - ARROW_LEFT: 37, - ARROW_UP: 38, - ARROW_RIGHT: 39, - ARROW_DOWN: 40, - PRINT: 44, - INSERT: 45, - DELETE: 46, - DIGIT_0: 48, - DIGIT_1: 49, - DIGIT_2: 50, - DIGIT_3: 51, - DIGIT_4: 52, - DIGIT_5: 53, - DIGIT_6: 54, - DIGIT_7: 55, - DIGIT_8: 56, - DIGIT_9: 57, - A: 65, - B: 66, - C: 67, - D: 68, - E: 69, - F: 70, - G: 71, - H: 72, - I: 73, - J: 74, - K: 75, - L: 76, - M: 77, - N: 78, - O: 79, - P: 80, - Q: 81, - R: 82, - S: 83, - T: 84, - U: 85, - V: 86, - W: 87, - X: 88, - Y: 89, - Z: 90, - WINDOWS: 91, - CONTEXT_MENU: 93, - TURN_OFF: 94, - SLEEP: 95, - NUMPAD_0: 96, - NUMPAD_1: 97, - NUMPAD_2: 98, - NUMPAD_3: 99, - NUMPAD_4: 100, - NUMPAD_5: 101, - NUMPAD_6: 102, - NUMPAD_7: 103, - NUMPAD_8: 104, - NUMPAD_9: 105, - NUMPAD_ASTERISK: 106, - NUMPAD_PLUS: 107, - NUMPAD_MINUS: 109, - NUMPAD_COMMA: 110, - NUMPAD_SLASH: 111, - F1: 112, - F2: 113, - F3: 114, - F4: 115, - F5: 116, - F6: 117, - F7: 118, - F8: 119, - F9: 120, - F10: 121, - F11: 122, - F12: 123, - NUM_LOCK: 144, - SCROLL_LOCK: 145, - COLON: 186, - PLUS: 187, - COMMA: 188, - SLASH: 189, - DOT: 190, - PIPE: 191, - SEMICOLON: 192, - MINUS: 219, - GREAT_ACCENT: 220, - EQUALS: 221, - SINGLE_QUOTE: 222, - BACKSLASH: 226, - }; - const isEnter = (event) => (event.key ? event.key === "Enter" : event.keyCode === KeyCodes.ENTER) && !hasModifierKeys(event); - const isSpace = (event) => (event.key ? (event.key === "Spacebar" || event.key === " ") : event.keyCode === KeyCodes.SPACE) && !hasModifierKeys(event); - const hasModifierKeys = (event) => event.shiftKey || event.altKey || getCtrlKey(event); - const getCtrlKey = (event) => !!(event.metaKey || event.ctrlKey); // double negation doesn't have effect on boolean but ensures null and undefined are equivalent to false. + const d$7=(r,n)=>{const e=document.createElement("link");return e.type="text/css",e.rel="stylesheet",n&&Object.entries(n).forEach(t=>e.setAttribute(...t)),e.href=r,document.head.appendChild(e),new Promise(t=>{e.addEventListener("load",t),e.addEventListener("error",t);})}; - /** - * Different navigation modes for ItemNavigation. - * - * @public - */ - var NavigationMode; - (function (NavigationMode) { - /** - * @public - */ - NavigationMode["Auto"] = "Auto"; - /** - * @public - */ - NavigationMode["Vertical"] = "Vertical"; - /** - * @public - */ - NavigationMode["Horizontal"] = "Horizontal"; - /** - * @public - */ - NavigationMode["Paging"] = "Paging"; - })(NavigationMode || (NavigationMode = {})); + let t$d;i$l(()=>{t$d=void 0;});const n$f=()=>(t$d===void 0&&(t$d=S$6()),t$d),u$8=e=>`${n$f()}Base/baseLib/${e}/css_variables.css`,i$e=async e=>{const o=document.querySelector(`[sap-ui-webcomponents-theme="${e}"]`);o&&document.head.removeChild(o),await d$7(u$8(e),{"sap-ui-webcomponents-theme":e});}; - /** - * Different behavior for ItemNavigation. - * - * @public - */ - var ItemNavigationBehavior; - (function (ItemNavigationBehavior) { - /** - * Static behavior: navigations stops at the first or last item. - * @public - */ - ItemNavigationBehavior["Static"] = "Static"; - /** - * Cycling behavior: navigating past the last item continues with the first and vice versa. - * @public - */ - ItemNavigationBehavior["Cyclic"] = "Cyclic"; - })(ItemNavigationBehavior || (ItemNavigationBehavior = {})); - - const kebabToCamelMap = new Map(); - const camelToKebabMap = new Map(); - const kebabToPascalMap = new Map(); - const kebabToCamelCase = (string) => { - if (!kebabToCamelMap.has(string)) { - const result = toCamelCase(string.split("-")); - kebabToCamelMap.set(string, result); - } - return kebabToCamelMap.get(string); - }; - const camelToKebabCase = (string) => { - if (!camelToKebabMap.has(string)) { - const result = string.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); - camelToKebabMap.set(string, result); - } - return camelToKebabMap.get(string); - }; - const toCamelCase = (parts) => { - return parts.map((string, index) => { - return index === 0 ? string.toLowerCase() : string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); - }).join(""); - }; - const kebabToPascalCase = (src) => { - const cachedName = kebabToPascalMap.get(src); - if (cachedName) { - return cachedName; - } - const camelStr = kebabToCamelCase(src); - const result = camelStr.charAt(0).toUpperCase() + camelStr.slice(1); - kebabToPascalMap.set(src, result); - return result; - }; + const s$f="@ui5/webcomponents-theming",S$3=()=>$$1().has(s$f),P$1=async e=>{if(!S$3())return;const t=await P$2(s$f,e);t&&m$8(t,"data-ui5-theme-properties",s$f,e);},E$2=()=>{p$7("data-ui5-theme-properties",s$f);},U=async(e,t)=>{const o=[...$$1()].map(async a=>{if(a===s$f)return;const i=await P$2(a,e,t);i&&m$8(i,`data-ui5-component-properties-${I$5()}`,a);});return Promise.all(o)},w$4=async e=>{const t=m$7();if(t)return t;const r=m$d("OpenUI5Support");if(r&&r.isOpenUI5Detected()){if(r.cssVariablesLoaded())return {themeName:r.getConfigurationSettingsObject()?.theme,baseThemeName:""}}else if(n$f())return await i$e(e),m$7()},I$3=async e=>{const t=await w$4(e);!t||e!==t.themeName?await P$1(e):E$2();const r=D$2(e)?e:t&&t.baseThemeName;await U(r||e$g,t&&t.themeName===e?e:void 0),r$e(e);}; - /** - * Determines the slot to which a node should be assigned - * @param node Text node or HTML element - * @returns {string} - */ - const getSlotName = (node) => { - // Text nodes can only go to the default slot - if (!(node instanceof HTMLElement)) { - return "default"; - } - // Discover the slot based on the real slot name (f.e. footer => footer, or content-32 => content) - const slot = node.getAttribute("slot"); - if (slot) { - const match = slot.match(/^(.+?)-\d+$/); - return match ? match[1] : slot; - } - // Use default slot as a fallback - return "default"; - }; - const getSlottedNodes = (node) => { - if (node instanceof HTMLSlotElement) { - return node.assignedNodes({ flatten: true }).filter(item => item instanceof HTMLElement); - } - return [node]; - }; - const getSlottedNodesList = (nodeList) => { - return nodeList.reduce((acc, curr) => acc.concat(getSlottedNodes(curr)), []); - }; + const d$6=()=>new Promise(e=>{document.body?e():document.addEventListener("DOMContentLoaded",()=>{e();});}); - /** - * @class - * @public - */ - class UI5ElementMetadata { - constructor(metadata) { - this.metadata = metadata; - } - getInitialState() { - if (Object.prototype.hasOwnProperty.call(this, "_initialState")) { - return this._initialState; - } - const initialState = {}; - const slotsAreManaged = this.slotsAreManaged(); - // Initialize slots - if (slotsAreManaged) { - const slots = this.getSlots(); - for (const [slotName, slotData] of Object.entries(slots)) { // eslint-disable-line - const propertyName = slotData.propertyName || slotName; - initialState[propertyName] = []; - initialState[kebabToCamelCase(propertyName)] = initialState[propertyName]; - } - } - this._initialState = initialState; - return initialState; - } - /** - * Validates the slot's value and returns it if correct - * or throws an exception if not. - * **Note:** Only intended for use by UI5Element.js - * @public - */ - static validateSlotValue(value, slotData) { - return validateSingleSlot(value, slotData); - } - /** - * Returns the tag of the UI5 Element without the scope - * @public - */ - getPureTag() { - return this.metadata.tag || ""; - } - /** - * Returns the tag of the UI5 Element without the scope - * @private - */ - getFeatures() { - return this.metadata.features || []; - } - /** - * Returns the tag of the UI5 Element - * @public - */ - getTag() { - const pureTag = this.metadata.tag; - if (!pureTag) { - return ""; - } - const suffix = getEffectiveScopingSuffixForTag(pureTag); - if (!suffix) { - return pureTag; - } - return `${pureTag}-${suffix}`; - } - /** - * Determines whether a property should have an attribute counterpart - * @public - * @param propName - */ - hasAttribute(propName) { - const propData = this.getProperties()[propName]; - return propData.type !== Object && propData.type !== Array && !propData.noAttribute; - } - /** - * Returns an array with the properties of the UI5 Element (in camelCase) - * @public - */ - getPropertiesList() { - return Object.keys(this.getProperties()); - } - /** - * Returns an array with the attributes of the UI5 Element (in kebab-case) - * @public - */ - getAttributesList() { - return this.getPropertiesList().filter(this.hasAttribute.bind(this)).map(camelToKebabCase); - } - /** - * Determines whether this UI5 Element has a default slot of type Node, therefore can slot text - */ - canSlotText() { - return (this.getSlots().default)?.type === Node; - } - /** - * Determines whether this UI5 Element supports any slots - * @public - */ - hasSlots() { - return !!Object.entries(this.getSlots()).length; - } - /** - * Determines whether this UI5 Element supports any slots with "individualSlots: true" - * @public - */ - hasIndividualSlots() { - return this.slotsAreManaged() && Object.values(this.getSlots()).some(slotData => slotData.individualSlots); - } - /** - * Determines whether this UI5 Element needs to invalidate if children are added/removed/changed - * @public - */ - slotsAreManaged() { - return !!this.metadata.managedSlots; - } - /** - * Determines whether this control supports F6 fast navigation - * @public - */ - supportsF6FastNavigation() { - return !!this.metadata.fastNavigation; - } - /** - * Returns an object with key-value pairs of properties and their metadata definitions - * @public - */ - getProperties() { - if (!this.metadata.properties) { - this.metadata.properties = {}; - } - return this.metadata.properties; - } - /** - * Returns an object with key-value pairs of events and their metadata definitions - * @public - */ - getEvents() { - if (!this.metadata.events) { - this.metadata.events = {}; - } - return this.metadata.events; - } - /** - * Returns an object with key-value pairs of slots and their metadata definitions - * @public - */ - getSlots() { - if (!this.metadata.slots) { - this.metadata.slots = {}; - } - return this.metadata.slots; - } - /** - * Determines whether this UI5 Element has any translatable texts (needs to be invalidated upon language change) - */ - isLanguageAware() { - return !!this.metadata.languageAware; - } - /** - * Determines whether this UI5 Element has any theme dependant carachteristics. - */ - isThemeAware() { - return !!this.metadata.themeAware; - } - /** - * Determines whether this UI5 Element needs CLDR assets to be fetched to work correctly - */ - needsCLDR() { - return !!this.metadata.cldr; - } - getShadowRootOptions() { - return this.metadata.shadowRootOptions || {}; - } - /** - * Determines whether this UI5 Element has any theme dependant carachteristics. - */ - isFormAssociated() { - return !!this.metadata.formAssociated; - } - /** - * Matches a changed entity (property/slot) with the given name against the "invalidateOnChildChange" configuration - * and determines whether this should cause and invalidation - * - * @param slotName the name of the slot in which a child was changed - * @param type the type of change in the child: "property" or "slot" - * @param name the name of the property/slot that changed - */ - shouldInvalidateOnChildChange(slotName, type, name) { - const config = this.getSlots()[slotName].invalidateOnChildChange; - // invalidateOnChildChange was not set in the slot metadata - by default child changes do not affect the component - if (config === undefined) { - return false; - } - // The simple format was used: invalidateOnChildChange: true/false; - if (typeof config === "boolean") { - return config; - } - // The complex format was used: invalidateOnChildChange: { properties, slots } - if (typeof config === "object") { - // A property was changed - if (type === "property") { - // The config object does not have a properties field - if (config.properties === undefined) { - return false; - } - // The config object has the short format: properties: true/false - if (typeof config.properties === "boolean") { - return config.properties; - } - // The config object has the complex format: properties: [...] - if (Array.isArray(config.properties)) { - return config.properties.includes(name); - } - throw new Error("Wrong format for invalidateOnChildChange.properties: boolean or array is expected"); - } - // A slot was changed - if (type === "slot") { - // The config object does not have a slots field - if (config.slots === undefined) { - return false; - } - // The config object has the short format: slots: true/false - if (typeof config.slots === "boolean") { - return config.slots; - } - // The config object has the complex format: slots: [...] - if (Array.isArray(config.slots)) { - return config.slots.includes(name); - } - throw new Error("Wrong format for invalidateOnChildChange.slots: boolean or array is expected"); - } - } - throw new Error("Wrong format for invalidateOnChildChange: boolean or object is expected"); - } - getI18n() { - if (!this.metadata.i18n) { - this.metadata.i18n = {}; - } - return this.metadata.i18n; - } - } - const validateSingleSlot = (value, slotData) => { - value && getSlottedNodes(value).forEach(el => { - if (!(el instanceof slotData.type)) { - throw new Error(`The element is not of type ${slotData.type.toString()}`); - } - }); - return value; - }; - - const getEventProvider = () => getSharedResource("CustomStyle.eventProvider", new EventProvider()); - const CUSTOM_CSS_CHANGE = "CustomCSSChange"; - const attachCustomCSSChange = (listener) => { - getEventProvider().attachEvent(CUSTOM_CSS_CHANGE, listener); - }; - const getCustomCSSFor = () => getSharedResource("CustomStyle.customCSSFor", {}); - attachCustomCSSChange((tag) => { - { - reRenderAllUI5Elements({ tag }); - } - }); - const getCustomCSS = (tag) => { - const customCSSFor = getCustomCSSFor(); - return customCSSFor[tag] ? customCSSFor[tag].join("") : ""; - }; - - const MAX_DEPTH_INHERITED_CLASSES = 10; // TypeScript complains about Infinity and big numbers - const getStylesString = (styles) => { - if (Array.isArray(styles)) { - return styles.filter(style => !!style).flat(MAX_DEPTH_INHERITED_CLASSES).map((style) => { - return typeof style === "string" ? style : style.content; - }).join(" "); - } - return typeof styles === "string" ? styles : styles.content; - }; - - const effectiveStyleMap = new Map(); - attachCustomCSSChange((tag) => { - effectiveStyleMap.delete(`${tag}_normal`); // there is custom CSS only for the component itself, not for its static area part - }); - const getEffectiveStyle = (ElementClass) => { - const tag = ElementClass.getMetadata().getTag(); - const key = `${tag}_normal`; - const openUI5Enablement = getFeature("OpenUI5Enablement"); - if (!effectiveStyleMap.has(key)) { - let busyIndicatorStyles = ""; - if (openUI5Enablement) { - busyIndicatorStyles = getStylesString(openUI5Enablement.getBusyIndicatorStyles()); - } - const customStyle = getCustomCSS(tag) || ""; - const builtInStyles = getStylesString(ElementClass.styles); - const effectiveStyle = `${builtInStyles} ${customStyle} ${busyIndicatorStyles}`; - effectiveStyleMap.set(key, effectiveStyle); - } - return effectiveStyleMap.get(key); // The key is guaranteed to exist - }; - - const constructableStyleMap = new Map(); - attachCustomCSSChange((tag) => { - constructableStyleMap.delete(`${tag}_normal`); // there is custom CSS only for the component itself, not for its static area part - }); - /** - * Returns (and caches) a constructable style sheet for a web component class - * Note: Chrome - * @param ElementClass - * @returns {*} - */ - const getConstructableStyle = (ElementClass) => { - const tag = ElementClass.getMetadata().getTag(); - const key = `${tag}_normal`; - if (!constructableStyleMap.has(key)) { - const styleContent = getEffectiveStyle(ElementClass); - const style = new CSSStyleSheet(); - style.replaceSync(styleContent); - constructableStyleMap.set(key, [style]); - } - return constructableStyleMap.get(key); - }; - - /** - * Updates the shadow root of a UI5Element or its static area item - * @param element - */ - const updateShadowRoot = (element) => { - const ctor = element.constructor; - const shadowRoot = element.shadowRoot; - const renderResult = element.render(); // this is checked before calling updateShadowRoot - if (!shadowRoot) { - console.warn(`There is no shadow root to update`); // eslint-disable-line - return; - } - shadowRoot.adoptedStyleSheets = getConstructableStyle(ctor); - ctor.renderer(renderResult, shadowRoot, { host: element }); - }; - - /** - * The tag prefixes to be ignored. - */ - const tagPrefixes = []; - /** - * Determines whether custom elements with the given tag should be ignored. - * - * @private - * @param { string } tag - */ - const shouldIgnoreCustomElement = (tag) => { - return tagPrefixes.some(pref => tag.startsWith(pref)); - }; - - const observers = new WeakMap(); - /** - * @param node - * @param callback - * @param options - */ - const observeDOMNode = (node, callback, options) => { - const observer = new MutationObserver(callback); - observers.set(node, observer); - observer.observe(node, options); - }; - /** - * @param node - */ - const unobserveDOMNode = (node) => { - const observer = observers.get(node); - if (observer) { - observer.disconnect(); - observers.delete(node); - } - }; - - const getEffectiveDir = (element) => { - if (element.matches(":dir(rtl)")) { - return "rtl"; - } - return "ltr"; - }; - - // Note: disabled is present in IE so we explicitly allow it here. - // Others, such as title/hidden, we explicitly override, so valid too - const allowList = [ - "disabled", - "title", - "hidden", - "role", - "draggable", - ]; - /** - * Checks whether a property name is valid (does not collide with existing DOM API properties) - * - * @param name - * @returns {boolean} - */ - const isValidPropertyName = (name) => { - if (allowList.includes(name) || name.startsWith("aria")) { - return true; - } - const classes = [ - HTMLElement, - Element, - Node, - ]; - return !classes.some(klass => klass.prototype.hasOwnProperty(name)); // eslint-disable-line - }; - - const arraysAreEqual = (arr1, arr2) => { - if (arr1.length !== arr2.length) { - return false; - } - for (let i = 0; i < arr1.length; i++) { - if (arr1[i] !== arr2[i]) { - return false; - } - } - return true; - }; - - /** - * Runs a component's template with the component's current state, while also scoping HTML - * - * @param template - the template to execute - * @param component - the component - * @public - */ - const executeTemplate = (template, component) => { - const tagsToScope = getTagsToScope(component); - const scope = getCustomElementsScopingSuffix(); - return template.call(component, component, tagsToScope, scope); - }; - /** - * Returns all tags, used inside component's template subject to scoping. - * @param component - the component - * @returns {Array[]} - * @private - */ - const getTagsToScope = (component) => { - const ctor = component.constructor; - const componentTag = ctor.getMetadata().getPureTag(); - const tagsToScope = ctor.getUniqueDependencies().map((dep) => dep.getMetadata().getPureTag()).filter(shouldScopeCustomElement); - if (shouldScopeCustomElement(componentTag)) { - tagsToScope.push(componentTag); - } - return tagsToScope; - }; - - const updateFormValue = (element) => { - if (isInputElement(element)) { - setFormValue(element); - } - }; - const setFormValue = (element) => { - if (!element._internals?.form) { - return; - } - setFormValidity(element); - if (!element.name) { - element._internals?.setFormValue(null); - return; - } - element._internals.setFormValue(element.formFormattedValue); - }; - const setFormValidity = async (element) => { - if (!element._internals?.form) { - return; - } - if (element.formValidity && Object.keys(element.formValidity).some(key => key)) { - const focusRef = await element.formElementAnchor?.(); - element._internals.setValidity(element.formValidity, element.formValidityMessage, focusRef); - } - else { - element._internals.setValidity({}); - } - }; - const isInputElement = (element) => { - return "formFormattedValue" in element && "name" in element; - }; - - const isSSR = typeof document === "undefined"; - const detectNavigatorLanguage = () => { - if (isSSR) { - return DEFAULT_LANGUAGE; - } - const browserLanguages = navigator.languages; - const navigatorLanguage = () => { - return navigator.language; - }; - const rawLocale = (browserLanguages && browserLanguages[0]) || navigatorLanguage(); - return rawLocale || DEFAULT_LANGUAGE; - }; - - const rLocale = /^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i; - class Locale { - constructor(sLocaleId) { - const aResult = rLocale.exec(sLocaleId.replace(/_/g, "-")); - if (aResult === null) { - throw new Error(`The given language ${sLocaleId} does not adhere to BCP-47.`); - } - this.sLocaleId = sLocaleId; - this.sLanguage = aResult[1] || DEFAULT_LANGUAGE; - this.sScript = aResult[2] || ""; - this.sRegion = aResult[3] || ""; - this.sVariant = (aResult[4] && aResult[4].slice(1)) || null; - this.sExtension = (aResult[5] && aResult[5].slice(1)) || null; - this.sPrivateUse = aResult[6] || null; - if (this.sLanguage) { - this.sLanguage = this.sLanguage.toLowerCase(); - } - if (this.sScript) { - this.sScript = this.sScript.toLowerCase().replace(/^[a-z]/, s => { - return s.toUpperCase(); - }); - } - if (this.sRegion) { - this.sRegion = this.sRegion.toUpperCase(); - } - } - getLanguage() { - return this.sLanguage; - } - getScript() { - return this.sScript; - } - getRegion() { - return this.sRegion; - } - getVariant() { - return this.sVariant; - } - getVariantSubtags() { - return this.sVariant ? this.sVariant.split("-") : []; - } - getExtension() { - return this.sExtension; - } - getExtensionSubtags() { - return this.sExtension ? this.sExtension.slice(2).split("-") : []; - } - getPrivateUse() { - return this.sPrivateUse; - } - getPrivateUseSubtags() { - return this.sPrivateUse ? this.sPrivateUse.slice(2).split("-") : []; - } - hasPrivateUseSubtag(sSubtag) { - return this.getPrivateUseSubtags().indexOf(sSubtag) >= 0; - } - toString() { - const r = [this.sLanguage]; - if (this.sScript) { - r.push(this.sScript); - } - if (this.sRegion) { - r.push(this.sRegion); - } - if (this.sVariant) { - r.push(this.sVariant); - } - if (this.sExtension) { - r.push(this.sExtension); - } - if (this.sPrivateUse) { - r.push(this.sPrivateUse); - } - return r.join("-"); - } - } - - const cache = new Map(); - const getLocaleInstance = (lang) => { - if (!cache.has(lang)) { - cache.set(lang, new Locale(lang)); - } - return cache.get(lang); - }; - const convertToLocaleOrNull = (lang) => { - try { - if (lang && typeof lang === "string") { - return getLocaleInstance(lang); - } - } - catch (e) { - // ignore - } - return new Locale(DEFAULT_LOCALE); - }; - /** - * Returns the locale based on the parameter or configured language Configuration#getLanguage - * If no language has been configured - a new locale based on browser language is returned - */ - const getLocale = (lang) => { - const configLanguage = getLanguage(); - if (configLanguage) { - return getLocaleInstance(configLanguage); - } - return convertToLocaleOrNull(detectNavigatorLanguage()); - }; - - const localeRegEX = /^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i; - const SAPSupportabilityLocales = /(?:^|-)(saptrc|sappsd)(?:-|$)/i; - /* Map for old language names for a few ISO639 codes. */ - const M_ISO639_NEW_TO_OLD = { - "he": "iw", - "yi": "ji", - "nb": "no", - "sr": "sh", - }; - /** - * Normalizes the given locale in BCP-47 syntax. - * @param {string} locale locale to normalize - * @returns {string} Normalized locale, "undefined" if the locale can't be normalized or the default locale, if no locale provided. - */ - const normalizeLocale = (locale) => { - let m; - if (!locale) { - return DEFAULT_LOCALE; - } - if (typeof locale === "string" && (m = localeRegEX.exec(locale.replace(/_/g, "-")))) { /* eslint-disable-line */ - let language = m[1].toLowerCase(); - let region = m[3] ? m[3].toUpperCase() : undefined; - const script = m[2] ? m[2].toLowerCase() : undefined; - const variants = m[4] ? m[4].slice(1) : undefined; - const isPrivate = m[6]; - language = M_ISO639_NEW_TO_OLD[language] || language; - // recognize and convert special SAP supportability locales (overwrites m[]!) - if ((isPrivate && (m = SAPSupportabilityLocales.exec(isPrivate))) /* eslint-disable-line */ || - (variants && (m = SAPSupportabilityLocales.exec(variants)))) { /* eslint-disable-line */ - return `en_US_${m[1].toLowerCase()}`; // for now enforce en_US (agreed with SAP SLS) - } - // Chinese: when no region but a script is specified, use default region for each script - if (language === "zh" && !region) { - if (script === "hans") { - region = "CN"; - } - else if (script === "hant") { - region = "TW"; - } - } - return language + (region ? "_" + region + (variants ? "_" + variants.replace("-", "_") : "") : ""); /* eslint-disable-line */ - } - return DEFAULT_LOCALE; - }; - - /** - * Calculates the next fallback locale for the given locale. - * - * @param {string} locale Locale string in Java format (underscores) or null - * @returns {string} Next fallback Locale or "en" if no fallbacks found. - */ - const nextFallbackLocale = (locale) => { - if (!locale) { - return DEFAULT_LOCALE; - } - if (locale === "zh_HK") { - return "zh_TW"; - } - // if there are multiple segments (separated by underscores), remove the last one - const p = locale.lastIndexOf("_"); - if (p >= 0) { - return locale.slice(0, p); - } - // for any language but the default, fallback to the default first before falling back to the 'raw' language (empty string) - return locale !== DEFAULT_LOCALE ? DEFAULT_LOCALE : ""; - }; - - // contains package names for which the warning has been shown - const warningShown$1 = new Set(); - const reportedErrors$1 = new Set(); - const bundleData = new Map(); - const bundlePromises = new Map(); - const loaders$2 = new Map(); - const _setI18nBundleData = (packageName, data) => { - bundleData.set(packageName, data); - }; - const getI18nBundleData = (packageName) => { - return bundleData.get(packageName); - }; - const _hasLoader = (packageName, localeId) => { - const bundleKey = `${packageName}/${localeId}`; - return loaders$2.has(bundleKey); - }; - // load bundle over the network once - const _loadMessageBundleOnce = (packageName, localeId) => { - const bundleKey = `${packageName}/${localeId}`; - const loadMessageBundle = loaders$2.get(bundleKey); - if (loadMessageBundle && !bundlePromises.get(bundleKey)) { - bundlePromises.set(bundleKey, loadMessageBundle(localeId)); - } - return bundlePromises.get(bundleKey); // Investigate if i18n loader exists and this won't return undefined. - }; - const _showAssetsWarningOnce$1 = (packageName) => { - if (!warningShown$1.has(packageName)) { - console.warn(`[${packageName}]: Message bundle assets are not configured. Falling back to English texts.`, /* eslint-disable-line */ ` Add \`import "${packageName}/dist/Assets.js"\` in your bundle and make sure your build tool supports dynamic imports and JSON imports. See section "Assets" in the documentation for more information.`); /* eslint-disable-line */ - warningShown$1.add(packageName); - } - }; - const useFallbackBundle = (packageName, localeId) => { - return localeId !== DEFAULT_LANGUAGE && !_hasLoader(packageName, localeId); - }; - /** - * This method preforms the asynchronous task of fetching the actual text resources. It will fetch - * each text resource over the network once (even for multiple calls to the same method). - * It should be fully finished before the i18nBundle class is created in the webcomponents. - * This method uses the bundle URLs that are populated by the `registerI18nBundle` method. - * To simplify the usage, the synchronization of both methods happens internally for the same `bundleId` - * @param {packageName} packageName the NPM package name - * @public - */ - const fetchI18nBundle = async (packageName) => { - const language = getLocale().getLanguage(); - const region = getLocale().getRegion(); - const variant = getLocale().getVariant(); - let localeId = language + (region ? `-${region}` : ``) + (variant ? `-${variant}` : ``); - if (useFallbackBundle(packageName, localeId)) { - localeId = normalizeLocale(localeId); - while (useFallbackBundle(packageName, localeId)) { - localeId = nextFallbackLocale(localeId); - } - } - // use default language unless configured to always fetch it from the network - const fetchDefaultLanguage = getFetchDefaultLanguage(); - if (localeId === DEFAULT_LANGUAGE && !fetchDefaultLanguage) { - _setI18nBundleData(packageName, null); // reset for the default language (if data was set for a previous language) - return; - } - if (!_hasLoader(packageName, localeId)) { - _showAssetsWarningOnce$1(packageName); - return; - } - try { - const data = await _loadMessageBundleOnce(packageName, localeId); - _setI18nBundleData(packageName, data); - } - catch (error) { - const e = error; - if (!reportedErrors$1.has(e.message)) { - reportedErrors$1.add(e.message); - console.error(e.message); /* eslint-disable-line */ - } - } - }; - // When the language changes dynamically (the user calls setLanguage), re-fetch all previously fetched bundles - attachLanguageChange((lang /* eslint-disable-line */) => { - const allPackages = [...bundleData.keys()]; - return Promise.all(allPackages.map(fetchI18nBundle)); - }); - - const messageFormatRegEX = /('')|'([^']+(?:''[^']*)*)(?:'|$)|\{([0-9]+(?:\s*,[^{}]*)?)\}|[{}]/g; - const formatMessage = (text, values) => { - values = values || []; - return text.replace(messageFormatRegEX, ($0, $1, $2, $3, offset) => { - if ($1) { - return '\''; /* eslint-disable-line */ - } - if ($2) { - return $2.replace(/''/g, '\''); /* eslint-disable-line */ - } - if ($3) { - const ind = typeof $3 === "string" ? parseInt($3) : $3; - return String(values[ind]); - } - throw new Error(`[i18n]: pattern syntax error at pos ${offset}`); - }); - }; - - const I18nBundleInstances = new Map(); - /** - * @class - * @public - */ - class I18nBundle { - constructor(packageName) { - this.packageName = packageName; - } - /** - * Returns a text in the currently loaded language - * - * @public - * @param textObj key/defaultText pair or just the key - * @param params Values for the placeholders - */ - getText(textObj, ...params) { - if (typeof textObj === "string") { - textObj = { key: textObj, defaultText: textObj }; - } - if (!textObj || !textObj.key) { - return ""; - } - const bundle = getI18nBundleData(this.packageName); - if (bundle && !bundle[textObj.key]) { - // eslint-disable-next-line no-console - console.warn(`Key ${textObj.key} not found in the i18n bundle, the default text will be used`); - } - const messageText = bundle && bundle[textObj.key] ? bundle[textObj.key] : (textObj.defaultText || textObj.key); - return formatMessage(messageText, params); - } - } - /** - * Returns the I18nBundle instance for the given package synchronously. - * - * @public - * @param packageName - */ - const getI18nBundleSync = (packageName) => { - if (I18nBundleInstances.has(packageName)) { - return I18nBundleInstances.get(packageName); - } - const i18nBundle = new I18nBundle(packageName); - I18nBundleInstances.set(packageName, i18nBundle); - return i18nBundle; - }; - /** - * Fetches and returns the I18nBundle instance for the given package. - * - * @public - * @param packageName - */ - const getI18nBundle = async (packageName) => { - await fetchI18nBundle(packageName); - return getI18nBundleSync(packageName); - }; - - const localeDataMap = new Map(); - const loaders$1 = new Map(); - const cldrPromises = new Map(); - const reportedErrors = new Set(); - let warningShown = false; - const M_ISO639_OLD_TO_NEW = { - "iw": "he", - "ji": "yi", - "in": "id", - }; - const _showAssetsWarningOnce = (localeId) => { - if (warningShown) { - return; - } - console.warn(`[LocaleData] Supported locale "${localeId}" not configured, import the "Assets.js" module from the webcomponents package you are using.`); /* eslint-disable-line */ - warningShown = true; - }; - const calcLocale = (language, region, script) => { - // normalize language and handle special cases - language = (language && M_ISO639_OLD_TO_NEW[language]) || language; - // Special case 1: in an SAP context, the inclusive language code "no" always means Norwegian Bokmal ("nb") - if (language === "no") { - language = "nb"; - } - // Special case 2: for Chinese, derive a default region from the script (this behavior is inherited from Java) - if (language === "zh" && !region) { - if (script === "Hans") { - region = "CN"; - } - else if (script === "Hant") { - region = "TW"; - } - } - // Special case 3: for Serbian, there are cyrillic and latin scripts, "sh" and "sr-latn" map to "latin", "sr" maps to cyrillic. - if (language === "sh" || (language === "sr" && script === "Latn")) { - language = "sr"; - region = "Latn"; - } - // try language + region - let localeId = `${language}_${region}`; - if (SUPPORTED_LOCALES.includes(localeId)) { - if (loaders$1.has(localeId)) { - // supported and has loader - return localeId; - } - // supported, no loader - fallback to default and warn - _showAssetsWarningOnce(localeId); - return DEFAULT_LOCALE; - } - // not supported, try language only - localeId = language; - if (SUPPORTED_LOCALES.includes(localeId)) { - if (loaders$1.has(localeId)) { - // supported and has loader - return localeId; - } - // supported, no loader - fallback to default and warn - _showAssetsWarningOnce(localeId); - return DEFAULT_LOCALE; - } - // not supported - fallback to default locale - return DEFAULT_LOCALE; - }; - // internal set data - const setLocaleData = (localeId, content) => { - localeDataMap.set(localeId, content); - }; - // load bundle over the network once - const _loadCldrOnce = (localeId) => { - if (!cldrPromises.get(localeId)) { - const loadCldr = loaders$1.get(localeId); - if (!loadCldr) { - throw new Error(`CLDR data for locale ${localeId} is not loaded!`); - } - cldrPromises.set(localeId, loadCldr(localeId)); - } - return cldrPromises.get(localeId); - }; - // external getAsync - const fetchCldr = async (language, region, script) => { - const localeId = calcLocale(language, region, script); - // reuse OpenUI5 CLDR if present - const openUI5Support = getFeature("OpenUI5Support"); - if (openUI5Support) { - const cldrContent = openUI5Support.getLocaleDataObject(); - if (cldrContent) { - // only if openui5 actually returned valid content - setLocaleData(localeId, cldrContent); - return; - } - } - // fetch it - try { - const cldrContent = await _loadCldrOnce(localeId); - setLocaleData(localeId, cldrContent); - } - catch (error) { - const e = error; - if (!reportedErrors.has(e.message)) { - reportedErrors.add(e.message); - console.error(e.message); /* eslint-disable-line */ - } - } - }; - const registerLocaleDataLoader = (localeId, loader) => { - loaders$1.set(localeId, loader); - }; - // register default loader for "en" from ui5 CDN (dev workflow without assets) - registerLocaleDataLoader("en", async () => { - const cldrContent = await fetch(`https://sdk.openui5.org/1.120.17/resources/sap/ui/core/cldr/en.json`); - return cldrContent.json(); - }); - // When the language changes dynamically (the user calls setLanguage), - // re-fetch the required CDRD data. - attachLanguageChange(() => { - const locale = getLocale(); - return fetchCldr(locale.getLanguage(), locale.getRegion(), locale.getScript()); - }); - - let autoId = 0; - const elementTimeouts = new Map(); - const uniqueDependenciesCache = new Map(); - const defaultConverter = { - fromAttribute(value, type) { - if (type === Boolean) { - return value !== null; - } - if (type === Number) { - return value === null ? undefined : parseFloat(value); - } - return value; - }, - toAttribute(value, type) { - if (type === Boolean) { - return value ? "" : null; - } - if (type === Object || type === Array) { - return null; - } - if (value === null || value === undefined) { - return null; - } - return String(value); - } - }; - function _invalidate(changeInfo) { - if (this._suppressInvalidation) { - return; - } - this.onInvalidation(changeInfo); - this._changedState.push(changeInfo); - renderDeferred(this); - this._invalidationEventProvider.fireEvent("invalidate", { - ...changeInfo, - target: this - }); - } - function getPropertyDescriptor(proto, name) { - do { - const descriptor = Object.getOwnPropertyDescriptor(proto, name); - if (descriptor) { - return descriptor; - } - proto = Object.getPrototypeOf(proto); - } while (proto && proto !== HTMLElement.prototype); - } - class UI5Element extends HTMLElement { - constructor() { - super(); - this._rendered = false; - const ctor = this.constructor; - this._changedState = []; - this._suppressInvalidation = true; - this._inDOM = false; - this._fullyConnected = false; - this._childChangeListeners = new Map(); - this._slotChangeListeners = new Map(); - this._invalidationEventProvider = new EventProvider(); - this._componentStateFinalizedEventProvider = new EventProvider(); - let deferredResolve; - this._domRefReadyPromise = new Promise(resolve => { - deferredResolve = resolve; - }); - this._domRefReadyPromise._deferredResolve = deferredResolve; - this._doNotSyncAttributes = new Set(); - this._slotsAssignedNodes = new WeakMap(); - this._state = { - ...ctor.getMetadata().getInitialState() - }; - this.initializedProperties = new Map(); - const allProps = this.constructor.getMetadata().getPropertiesList(); - allProps.forEach(propertyName => { - if (this.hasOwnProperty(propertyName)) { - const value = this[propertyName]; - this.initializedProperties.set(propertyName, value); - } - }); - this._internals = this.attachInternals(); - this._initShadowRoot(); - } - _initShadowRoot() { - const ctor = this.constructor; - if (ctor._needsShadowDOM()) { - const defaultOptions = { - mode: "open" - }; - this.attachShadow({ - ...defaultOptions, - ...ctor.getMetadata().getShadowRootOptions() - }); - const slotsAreManaged = ctor.getMetadata().slotsAreManaged(); - if (slotsAreManaged) { - this.shadowRoot.addEventListener("slotchange", this._onShadowRootSlotChange.bind(this)); - } - } - } - _onShadowRootSlotChange(e) { - const targetShadowRoot = e.target?.getRootNode(); - if (targetShadowRoot === this.shadowRoot) { - this._processChildren(); - } - } - get _id() { - if (!this.__id) { - this.__id = `ui5wc_${++autoId}`; - } - return this.__id; - } - render() { - const template = this.constructor.template; - return executeTemplate(template, this); - } - async connectedCallback() { - { - const rootNode = this.getRootNode(); - if (rootNode instanceof ShadowRoot && instanceOfUI5Element(rootNode.host)) { - const klass = rootNode.host.constructor; - const hasDependency = getTagsToScope(rootNode.host).includes(this.constructor.getMetadata().getPureTag()); - if (!hasDependency) { - console.error(`[UI5-FWK] ${this.constructor.getMetadata().getTag()} not found in dependencies of ${klass.getMetadata().getTag()}`); - } - } - } - { - const props = this.constructor.getMetadata().getProperties(); - for (const [prop, propData] of Object.entries(props)) { - if (Object.hasOwn(this, prop) && !this.initializedProperties.has(prop)) { - console.error(`[UI5-FWK] ${this.constructor.getMetadata().getTag()} has a property [${prop}] that is shadowed by the instance. Updates to this property will not invalidate the component. Possible reason is TS target ES2022 or TS useDefineForClassFields`); - } - } - } - const ctor = this.constructor; - this.setAttribute(ctor.getMetadata().getPureTag(), ""); - if (ctor.getMetadata().supportsF6FastNavigation()) { - this.setAttribute("data-sap-ui-fastnavgroup", "true"); - } - const slotsAreManaged = ctor.getMetadata().slotsAreManaged(); - this._inDOM = true; - if (slotsAreManaged) { - this._startObservingDOMChildren(); - await this._processChildren(); - } - if (!this._inDOM) { - return; - } - if (!ctor.asyncFinished) { - await ctor.definePromise; - } - renderImmediately(this); - this._domRefReadyPromise._deferredResolve(); - this._fullyConnected = true; - this.onEnterDOM(); - } - disconnectedCallback() { - const ctor = this.constructor; - const slotsAreManaged = ctor.getMetadata().slotsAreManaged(); - this._inDOM = false; - if (slotsAreManaged) { - this._stopObservingDOMChildren(); - } - if (this._fullyConnected) { - this.onExitDOM(); - this._fullyConnected = false; - } - this._domRefReadyPromise._deferredResolve(); - cancelRender(this); - } - onBeforeRendering() {} - onAfterRendering() {} - onEnterDOM() {} - onExitDOM() {} - _startObservingDOMChildren() { - const ctor = this.constructor; - const metadata = ctor.getMetadata(); - const shouldObserveChildren = metadata.hasSlots(); - if (!shouldObserveChildren) { - return; - } - const canSlotText = metadata.canSlotText(); - const mutationObserverOptions = { - childList: true, - subtree: canSlotText, - characterData: canSlotText - }; - observeDOMNode(this, this._processChildren.bind(this), mutationObserverOptions); - } - _stopObservingDOMChildren() { - unobserveDOMNode(this); - } - async _processChildren() { - const hasSlots = this.constructor.getMetadata().hasSlots(); - if (hasSlots) { - await this._updateSlots(); - } - } - async _updateSlots() { - const ctor = this.constructor; - const slotsMap = ctor.getMetadata().getSlots(); - const canSlotText = ctor.getMetadata().canSlotText(); - const domChildren = Array.from(canSlotText ? this.childNodes : this.children); - const slotsCachedContentMap = new Map(); - const propertyNameToSlotMap = new Map(); - for (const [slotName, slotData] of Object.entries(slotsMap)) { - const propertyName = slotData.propertyName || slotName; - propertyNameToSlotMap.set(propertyName, slotName); - slotsCachedContentMap.set(propertyName, [...this._state[propertyName]]); - this._clearSlot(slotName, slotData); - } - const autoIncrementMap = new Map(); - const slottedChildrenMap = new Map(); - const allChildrenUpgraded = domChildren.map(async (child, idx) => { - const slotName = getSlotName(child); - const slotData = slotsMap[slotName]; - if (slotData === undefined) { - if (slotName !== "default") { - const validValues = Object.keys(slotsMap).join(", "); - console.warn(`Unknown slotName: ${slotName}, ignoring`, child, `Valid values are: ${validValues}`); - } - return; - } - if (slotData.individualSlots) { - const nextIndex = (autoIncrementMap.get(slotName) || 0) + 1; - autoIncrementMap.set(slotName, nextIndex); - child._individualSlot = `${slotName}-${nextIndex}`; - } - if (child instanceof HTMLElement) { - const localName = child.localName; - const shouldWaitForCustomElement = localName.includes("-") && !shouldIgnoreCustomElement(localName); - if (shouldWaitForCustomElement) { - const isDefined = customElements.get(localName); - if (!isDefined) { - const whenDefinedPromise = customElements.whenDefined(localName); - let timeoutPromise = elementTimeouts.get(localName); - if (!timeoutPromise) { - timeoutPromise = new Promise(resolve => setTimeout(resolve, 1000)); - elementTimeouts.set(localName, timeoutPromise); - } - await Promise.race([whenDefinedPromise, timeoutPromise]); - } - customElements.upgrade(child); - } - } - child = ctor.getMetadata().constructor.validateSlotValue(child, slotData); - if (instanceOfUI5Element(child) && slotData.invalidateOnChildChange) { - const childChangeListener = this._getChildChangeListener(slotName); - child.attachInvalidate.call(child, childChangeListener); - } - if (child instanceof HTMLSlotElement) { - this._attachSlotChange(child, slotName, !!slotData.invalidateOnChildChange); - } - const propertyName = slotData.propertyName || slotName; - if (slottedChildrenMap.has(propertyName)) { - slottedChildrenMap.get(propertyName).push({ - child, - idx - }); - } else { - slottedChildrenMap.set(propertyName, [{ - child, - idx - }]); - } - }); - await Promise.all(allChildrenUpgraded); - slottedChildrenMap.forEach((children, propertyName) => { - this._state[propertyName] = children.sort((a, b) => a.idx - b.idx).map(_ => _.child); - this._state[kebabToCamelCase(propertyName)] = this._state[propertyName]; - }); - let invalidated = false; - for (const [slotName, slotData] of Object.entries(slotsMap)) { - const propertyName = slotData.propertyName || slotName; - if (!arraysAreEqual(slotsCachedContentMap.get(propertyName), this._state[propertyName])) { - _invalidate.call(this, { - type: "slot", - name: propertyNameToSlotMap.get(propertyName), - reason: "children" - }); - invalidated = true; - if (ctor.getMetadata().isFormAssociated()) { - setFormValue(this); - } - } - } - if (!invalidated) { - _invalidate.call(this, { - type: "slot", - name: "default", - reason: "textcontent" - }); - } - } - _clearSlot(slotName, slotData) { - const propertyName = slotData.propertyName || slotName; - const children = this._state[propertyName]; - children.forEach(child => { - if (instanceOfUI5Element(child)) { - const childChangeListener = this._getChildChangeListener(slotName); - child.detachInvalidate.call(child, childChangeListener); - } - if (child instanceof HTMLSlotElement) { - this._detachSlotChange(child, slotName); - } - }); - this._state[propertyName] = []; - this._state[kebabToCamelCase(propertyName)] = this._state[propertyName]; - } - attachInvalidate(callback) { - this._invalidationEventProvider.attachEvent("invalidate", callback); - } - detachInvalidate(callback) { - this._invalidationEventProvider.detachEvent("invalidate", callback); - } - _onChildChange(slotName, childChangeInfo) { - if (!this.constructor.getMetadata().shouldInvalidateOnChildChange(slotName, childChangeInfo.type, childChangeInfo.name)) { - return; - } - _invalidate.call(this, { - type: "slot", - name: slotName, - reason: "childchange", - child: childChangeInfo.target - }); - } - attributeChangedCallback(name, oldValue, newValue) { - let newPropertyValue; - if (this._doNotSyncAttributes.has(name)) { - return; - } - const properties = this.constructor.getMetadata().getProperties(); - const realName = name.replace(/^ui5-/, ""); - const nameInCamelCase = kebabToCamelCase(realName); - if (properties.hasOwnProperty(nameInCamelCase)) { - const propData = properties[nameInCamelCase]; - const converter = propData.converter ?? defaultConverter; - newPropertyValue = converter.fromAttribute(newValue, propData.type); - this[nameInCamelCase] = newPropertyValue; - } - } - formAssociatedCallback() { - const ctor = this.constructor; - if (!ctor.getMetadata().isFormAssociated()) { - return; - } - updateFormValue(this); - } - static get formAssociated() { - return this.getMetadata().isFormAssociated(); - } - _updateAttribute(name, newValue) { - const ctor = this.constructor; - if (!ctor.getMetadata().hasAttribute(name)) { - return; - } - const properties = ctor.getMetadata().getProperties(); - const propData = properties[name]; - const attrName = camelToKebabCase(name); - const converter = propData.converter || defaultConverter; - { - const tag = this.constructor.getMetadata().getTag(); - if (typeof newValue === "boolean" && propData.type !== Boolean) { - console.error(`[UI5-FWK] boolean value for property [${name}] of component [${tag}] is missing "{ type: Boolean }" in its property decorator. Attribute conversion will treat it as a string. If this is intended, pass the value converted to string, otherwise add the type to the property decorator`); - } - if (typeof newValue === "number" && propData.type !== Number) { - console.error(`[UI5-FWK] numeric value for property [${name}] of component [${tag}] is missing "{ type: Number }" in its property decorator. Attribute conversion will treat it as a string. If this is intended, pass the value converted to string, otherwise add the type to the property decorator`); - } - if (typeof newValue === "string" && propData.type && propData.type !== String) { - console.error(`[UI5-FWK] string value for property [${name}] of component [${tag}] which has a non-string type [${propData.type}] in its property decorator. Attribute conversion will stop and keep the string value in the property.`); - } - } - const newAttrValue = converter.toAttribute(newValue, propData.type); - this._doNotSyncAttributes.add(attrName); - if (newAttrValue === null || newAttrValue === undefined) { - this.removeAttribute(attrName); - } else { - this.setAttribute(attrName, newAttrValue); - } - this._doNotSyncAttributes.delete(attrName); - } - _getChildChangeListener(slotName) { - if (!this._childChangeListeners.has(slotName)) { - this._childChangeListeners.set(slotName, this._onChildChange.bind(this, slotName)); - } - return this._childChangeListeners.get(slotName); - } - _getSlotChangeListener(slotName) { - if (!this._slotChangeListeners.has(slotName)) { - this._slotChangeListeners.set(slotName, this._onSlotChange.bind(this, slotName)); - } - return this._slotChangeListeners.get(slotName); - } - _attachSlotChange(slot, slotName, invalidateOnChildChange) { - const slotChangeListener = this._getSlotChangeListener(slotName); - slot.addEventListener("slotchange", e => { - slotChangeListener.call(slot, e); - if (invalidateOnChildChange) { - const previousChildren = this._slotsAssignedNodes.get(slot); - if (previousChildren) { - previousChildren.forEach(child => { - if (instanceOfUI5Element(child)) { - const childChangeListener = this._getChildChangeListener(slotName); - child.detachInvalidate.call(child, childChangeListener); - } - }); - } - const newChildren = getSlottedNodesList([slot]); - this._slotsAssignedNodes.set(slot, newChildren); - newChildren.forEach(child => { - if (instanceOfUI5Element(child)) { - const childChangeListener = this._getChildChangeListener(slotName); - child.attachInvalidate.call(child, childChangeListener); - } - }); - } - }); - } - _detachSlotChange(child, slotName) { - child.removeEventListener("slotchange", this._getSlotChangeListener(slotName)); - } - _onSlotChange(slotName) { - _invalidate.call(this, { - type: "slot", - name: slotName, - reason: "slotchange" - }); - } - onInvalidation(changeInfo) {} - updateAttributes() { - const ctor = this.constructor; - const props = ctor.getMetadata().getProperties(); - for (const [prop, propData] of Object.entries(props)) { - this._updateAttribute(prop, this[prop]); - } - } - _render() { - const ctor = this.constructor; - const hasIndividualSlots = ctor.getMetadata().hasIndividualSlots(); - if (this.initializedProperties.size > 0) { - Array.from(this.initializedProperties.entries()).forEach(([prop, value]) => { - delete this[prop]; - this[prop] = value; - }); - this.initializedProperties.clear(); - } - this._suppressInvalidation = true; - try { - this.onBeforeRendering(); - if (!this._rendered) { - this.updateAttributes(); - } - this._componentStateFinalizedEventProvider.fireEvent("componentStateFinalized"); - } finally { - this._suppressInvalidation = false; - } - this._changedState = []; - if (ctor._needsShadowDOM()) { - updateShadowRoot(this); - } - this._rendered = true; - if (hasIndividualSlots) { - this._assignIndividualSlotsToChildren(); - } - this.onAfterRendering(); - } - _assignIndividualSlotsToChildren() { - const domChildren = Array.from(this.children); - domChildren.forEach(child => { - if (child._individualSlot) { - child.setAttribute("slot", child._individualSlot); - } - }); - } - _waitForDomRef() { - return this._domRefReadyPromise; - } - getDomRef() { - if (typeof this._getRealDomRef === "function") { - return this._getRealDomRef(); - } - if (!this.shadowRoot || this.shadowRoot.children.length === 0) { - return; - } - return this.shadowRoot.children[0]; - } - getFocusDomRef() { - const domRef = this.getDomRef(); - if (domRef) { - const focusRef = domRef.querySelector("[data-sap-focus-ref]"); - return focusRef || domRef; - } - } - async getFocusDomRefAsync() { - await this._waitForDomRef(); - return this.getFocusDomRef(); - } - async focus(focusOptions) { - await this._waitForDomRef(); - const focusDomRef = this.getFocusDomRef(); - if (focusDomRef === this) { - HTMLElement.prototype.focus.call(this, focusOptions); - } else if (focusDomRef && typeof focusDomRef.focus === "function") { - focusDomRef.focus(focusOptions); - } - } - fireEvent(name, data, cancelable = false, bubbles = true) { - const eventResult = this._fireEvent(name, data, cancelable, bubbles); - const pascalCaseEventName = kebabToPascalCase(name); - if (pascalCaseEventName !== name) { - return eventResult && this._fireEvent(pascalCaseEventName, data, cancelable, bubbles); - } - return eventResult; - } - fireDecoratorEvent(name, data) { - const eventData = this.getEventData(name); - const cancellable = eventData ? eventData.cancelable : false; - const bubbles = eventData ? eventData.bubbles : false; - const eventResult = this._fireEvent(name, data, cancellable, bubbles); - const pascalCaseEventName = kebabToPascalCase(name); - if (pascalCaseEventName !== name) { - return eventResult && this._fireEvent(pascalCaseEventName, data, cancellable, bubbles); - } - return eventResult; - } - _fireEvent(name, data, cancelable = false, bubbles = true) { - const noConflictEvent = new CustomEvent(`ui5-${name}`, { - detail: data, - composed: false, - bubbles, - cancelable - }); - const noConflictEventResult = this.dispatchEvent(noConflictEvent); - if (skipOriginalEvent(name)) { - return noConflictEventResult; - } - const normalEvent = new CustomEvent(name, { - detail: data, - composed: false, - bubbles, - cancelable - }); - const normalEventResult = this.dispatchEvent(normalEvent); - return normalEventResult && noConflictEventResult; - } - getEventData(name) { - const ctor = this.constructor; - const eventMap = ctor.getMetadata().getEvents(); - return eventMap[name]; - } - getSlottedNodes(slotName) { - return getSlottedNodesList(this[slotName]); - } - attachComponentStateFinalized(callback) { - this._componentStateFinalizedEventProvider.attachEvent("componentStateFinalized", callback); - } - detachComponentStateFinalized(callback) { - this._componentStateFinalizedEventProvider.detachEvent("componentStateFinalized", callback); - } - get effectiveDir() { - markAsRtlAware(this.constructor); - return getEffectiveDir(this); - } - get isUI5Element() { - return true; - } - get classes() { - return {}; - } - get accessibilityInfo() { - return {}; - } - static get observedAttributes() { - return this.getMetadata().getAttributesList(); - } - static _needsShadowDOM() { - return !!this.template || Object.prototype.hasOwnProperty.call(this.prototype, "render"); - } - static _generateAccessors() { - const proto = this.prototype; - const slotsAreManaged = this.getMetadata().slotsAreManaged(); - const properties = this.getMetadata().getProperties(); - for (const [prop, propData] of Object.entries(properties)) { - if (!isValidPropertyName(prop)) { - console.warn(`"${prop}" is not a valid property name. Use a name that does not collide with DOM APIs`); - } - const descriptor = getPropertyDescriptor(proto, prop); - let origSet; - if (descriptor?.set) { - origSet = descriptor.set; - } - let origGet; - if (descriptor?.get) { - origGet = descriptor.get; - } - Object.defineProperty(proto, prop, { - get() { - if (origGet) { - return origGet.call(this); - } - return this._state[prop]; - }, - set(value) { - const ctor = this.constructor; - const oldState = origGet ? origGet.call(this) : this._state[prop]; - const isDifferent = oldState !== value; - if (isDifferent) { - if (origSet) { - origSet.call(this, value); - } else { - this._state[prop] = value; - } - _invalidate.call(this, { - type: "property", - name: prop, - newValue: value, - oldValue: oldState - }); - if (this._rendered) { - this._updateAttribute(prop, value); - } - if (ctor.getMetadata().isFormAssociated()) { - setFormValue(this); - } - } - } - }); - } - if (slotsAreManaged) { - const slots = this.getMetadata().getSlots(); - for (const [slotName, slotData] of Object.entries(slots)) { - if (!isValidPropertyName(slotName)) { - console.warn(`"${slotName}" is not a valid property name. Use a name that does not collide with DOM APIs`); - } - const propertyName = slotData.propertyName || slotName; - const propertyDescriptor = { - get() { - if (this._state[propertyName] !== undefined) { - return this._state[propertyName]; - } - return []; - }, - set() { - throw new Error("Cannot set slot content directly, use the DOM APIs (appendChild, removeChild, etc...)"); - } - }; - Object.defineProperty(proto, propertyName, propertyDescriptor); - if (propertyName !== kebabToCamelCase(propertyName)) { - Object.defineProperty(proto, kebabToCamelCase(propertyName), propertyDescriptor); - } - } - } - } - static get dependencies() { - return []; - } - static cacheUniqueDependencies() { - const filtered = this.dependencies.filter((dep, index, deps) => deps.indexOf(dep) === index); - uniqueDependenciesCache.set(this, filtered); - } - static getUniqueDependencies() { - if (!uniqueDependenciesCache.has(this)) { - this.cacheUniqueDependencies(); - } - return uniqueDependenciesCache.get(this) || []; - } - static async onDefine() { - return Promise.resolve(); - } - static fetchI18nBundles() { - return Promise.all(Object.entries(this.getMetadata().getI18n()).map(pair => { - const {bundleName} = pair[1]; - return getI18nBundle(bundleName); - })); - } - static fetchCLDR() { - if (this.getMetadata().needsCLDR()) { - return fetchCldr(getLocale().getLanguage(), getLocale().getRegion(), getLocale().getScript()); - } - return Promise.resolve(); - } - static define() { - const defineSequence = async () => { - await boot(); - const result = await Promise.all([this.fetchI18nBundles(), this.fetchCLDR(), this.onDefine()]); - const [i18nBundles] = result; - Object.entries(this.getMetadata().getI18n()).forEach((pair, index) => { - const propertyName = pair[0]; - const targetClass = pair[1].target; - targetClass[propertyName] = i18nBundles[index]; - }); - this.asyncFinished = true; - }; - this.definePromise = defineSequence(); - const tag = this.getMetadata().getTag(); - const features = this.getMetadata().getFeatures(); - features.forEach(feature => { - if (getComponentFeature(feature)) { - this.cacheUniqueDependencies(); - } - subscribeForFeatureLoad(feature, this, this.cacheUniqueDependencies.bind(this)); - }); - const definedLocally = isTagRegistered(tag); - const definedGlobally = customElements.get(tag); - if (definedGlobally && !definedLocally) { - recordTagRegistrationFailure(tag); - } else if (!definedGlobally) { - this._generateAccessors(); - registerTag(tag); - customElements.define(tag, this); - } - return this; - } - static getMetadata() { - if (this.hasOwnProperty("_metadata")) { - return this._metadata; - } - const metadataObjects = [this.metadata]; - let klass = this; - while (klass !== UI5Element) { - klass = Object.getPrototypeOf(klass); - metadataObjects.unshift(klass.metadata); - } - const mergedMetadata = fnMerge({}, ...metadataObjects); - this._metadata = new UI5ElementMetadata(mergedMetadata); - return this._metadata; - } - get validity() { - return this._internals.validity; - } - get validationMessage() { - return this._internals.validationMessage; - } - checkValidity() { - return this._internals.checkValidity(); - } - reportValidity() { - return this._internals.reportValidity(); - } - } - UI5Element.metadata = {}; - UI5Element.styles = ""; - const instanceOfUI5Element = object => { - return ("isUI5Element" in object); - }; + const o$e={packageName:"@ui5/webcomponents-base",fileName:"FontFace.css",content:`@font-face{font-family:"72";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular.woff2?ui5-webcomponents) format("woff2"),local("72");unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:400;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Regular-full.woff2?ui5-webcomponents) format("woff2"),local('72-full')}@font-face{font-family:"72";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:"72full";font-style:normal;font-weight:700;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Bold';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold.woff2?ui5-webcomponents) format("woff2"),local('72-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Boldfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Bold-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72-Light';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light.woff2?ui5-webcomponents) format("woff2"),local('72-Light');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72-Lightfull';font-style:normal;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Light-full.woff2?ui5-webcomponents) format("woff2")}@font-face{font-family:'72Mono';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular.woff2?ui5-webcomponents) format('woff2'),local('72Mono');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Monofull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Regular-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:'72Mono-Bold';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold.woff2?ui5-webcomponents) format('woff2'),local('72Mono-Bold');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Mono-Boldfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72Mono-Bold-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72Black";font-style:bold;font-weight:900;src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black.woff2?ui5-webcomponents) format("woff2"),local('72Black');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}@font-face{font-family:'72Blackfull';src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-Black-full.woff2?ui5-webcomponents) format('woff2')}@font-face{font-family:"72-SemiboldDuplex";src:url(https://sdk.openui5.org/resources/sap/ui/core/themes/sap_horizon/fonts/72-SemiboldDuplex.woff2?ui5-webcomponents) format("woff2"),local('72-SemiboldDuplex');unicode-range:U+00,U+0D,U+20-7E,U+A0-FF,U+131,U+152-153,U+161,U+178,U+17D-17E,U+192,U+237,U+2C6,U+2DC,U+3BC,U+1E9E,U+2013-2014,U+2018-201A,U+201C-201E,U+2020-2022,U+2026,U+2030,U+2039-203A,U+2044,U+20AC,U+2122}`}; - (function() { - /* Copyright Google Inc. - * Licensed under the Apache Licence Version 2.0 - * Autogenerated at Tue May 22 10:18:21 PDT 2012 - * \@overrides window - * \@provides cssSchema, CSS_PROP_BIT_QUANTITY, CSS_PROP_BIT_HASH_VALUE, CSS_PROP_BIT_NEGATIVE_QUANTITY, CSS_PROP_BIT_QSTRING_CONTENT, CSS_PROP_BIT_QSTRING_URL, CSS_PROP_BIT_HISTORY_INSENSITIVE, CSS_PROP_BIT_Z_INDEX, CSS_PROP_BIT_ALLOWED_IN_LINK */ - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_QUANTITY = 1; - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_HASH_VALUE = 2; - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_NEGATIVE_QUANTITY = 4; - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_QSTRING_CONTENT = 8; - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_QSTRING_URL = 16; - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_Z_INDEX = 64; - /** - * @const - * @type {number} - */ - var CSS_PROP_BIT_ALLOWED_IN_LINK = 128; - var cssSchema = (function () { - var s = [ - 'rgb(?:\\(\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)|a\\(\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0(?:\\.\\d+)?|\\.\\d+|1(?:\\.0+)?|0|\\d+(?:\\.\\d+)?%)) *\\)' - ], c = [ /^ *$/i, RegExp('^ *(?:\\s*' + s[ 0 ] + '|(?:\\s*' + s[ 0 ] + - ')?)+ *$', 'i'), RegExp('^ *\\s*' + s[ 0 ] + ' *$', 'i'), - RegExp('^ *\\s*' + s[ 0 ] + '\\s*' + s[ 0 ] + ' *$', 'i') ], L = [ [ - 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', - 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', - 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', - 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', - 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', - 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', - 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', - 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', - 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', - 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', - 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', - 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', - 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', - 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', - 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', - 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', - 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', - 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', - 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', - 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', - 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', - 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', - 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', - 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', - 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', - 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', - 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', - 'yellowgreen' ], [ 'all-scroll', 'col-resize', 'crosshair', 'default', - 'e-resize', 'hand', 'help', 'move', 'n-resize', 'ne-resize', 'no-drop', - 'not-allowed', 'nw-resize', 'pointer', 'progress', 'row-resize', - 's-resize', 'se-resize', 'sw-resize', 'text', 'vertical-text', - 'w-resize', 'wait' ], [ '-moz-inline-box', '-moz-inline-stack', - 'block', 'inline', 'inline-block', 'inline-table', 'list-item', - 'run-in', 'table', 'table-caption', 'table-cell', 'table-column', - 'table-column-group', 'table-footer-group', 'table-header-group', - 'table-row', 'table-row-group' ], [ 'armenian', 'circle', 'decimal', - 'decimal-leading-zero', 'disc', 'georgian', 'lower-alpha', - 'lower-greek', 'lower-latin', 'lower-roman', 'square', 'upper-alpha', - 'upper-latin', 'upper-roman' ], [ '100', '200', '300', '400', '500', - '600', '700', '800', '900', 'bold', 'bolder', 'lighter' ], [ - 'condensed', 'expanded', 'extra-condensed', 'extra-expanded', - 'narrower', 'semi-condensed', 'semi-expanded', 'ultra-condensed', - 'ultra-expanded', 'wider' ], [ 'behind', 'center-left', 'center-right', - 'far-left', 'far-right', 'left-side', 'leftwards', 'right-side', - 'rightwards' ], [ 'large', 'larger', 'small', 'smaller', 'x-large', - 'x-small', 'xx-large', 'xx-small' ], [ '-moz-pre-wrap', '-o-pre-wrap', - '-pre-wrap', 'nowrap', 'pre', 'pre-line', 'pre-wrap' ], [ 'dashed', - 'dotted', 'double', 'groove', 'outset', 'ridge', 'solid' ], [ - 'baseline', 'middle', 'sub', 'super', 'text-bottom', 'text-top' ], [ - 'caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar' - ], [ 'fast', 'faster', 'slow', 'slower', 'x-fast', 'x-slow' ], [ 'above', - 'below', 'higher', 'level', 'lower' ], [ 'border-box', 'contain', - 'content-box', 'cover', 'padding-box' ], [ 'cursive', 'fantasy', - 'monospace', 'sans-serif', 'serif' ], [ 'loud', 'silent', 'soft', - 'x-loud', 'x-soft' ], [ 'no-repeat', 'repeat-x', 'repeat-y', 'round', - 'space' ], [ 'blink', 'line-through', 'overline', 'underline' ], [ - 'high', 'low', 'x-high', 'x-low' ], [ 'absolute', 'relative', 'static' - ], [ 'capitalize', 'lowercase', 'uppercase' ], [ 'child', 'female', - 'male' ], [ 'bidi-override', 'embed' ], [ 'bottom', 'top' ], [ 'clip', - 'ellipsis' ], [ 'continuous', 'digits' ], [ 'hide', 'show' ], [ - 'inside', 'outside' ], [ 'italic', 'oblique' ], [ 'left', 'right' ], [ - 'ltr', 'rtl' ], [ 'no-content', 'no-display' ], [ 'suppress', - 'unrestricted' ], [ 'thick', 'thin' ], [ ',' ], [ '/' ], [ 'always' ], - [ 'auto' ], [ 'avoid' ], [ 'both' ], [ 'break-word' ], [ 'center' ], [ - 'code' ], [ 'collapse' ], [ 'fixed' ], [ 'hidden' ], [ 'inherit' ], [ - 'inset' ], [ 'invert' ], [ 'justify' ], [ 'local' ], [ 'medium' ], [ - 'mix' ], [ 'none' ], [ 'normal' ], [ 'once' ], [ 'repeat' ], [ 'scroll' - ], [ 'separate' ], [ 'small-caps' ], [ 'spell-out' ], [ 'transparent' ], - [ 'visible' ] ]; - return { - '-moz-border-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 36 ] ] - }, - '-moz-border-radius-bottomleft': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-moz-border-radius-bottomright': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-moz-border-radius-topleft': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-moz-border-radius-topright': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-moz-box-shadow': { - 'cssExtra': c[ 1 ], - 'cssAlternates': [ 'boxShadow' ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] - }, - '-moz-opacity': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 47 ] ] - }, - '-moz-outline': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 49 ], L[ 52 ], L[ 54 ] ] - }, - '-moz-outline-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 49 ] ] - }, - '-moz-outline-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - '-moz-outline-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - '-o-text-overflow': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 25 ] ] - }, - '-webkit-border-bottom-left-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-bottom-right-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 36 ] ] - }, - '-webkit-border-radius-bottom-left': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-radius-bottom-right': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-radius-top-left': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-radius-top-right': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-top-left-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-border-top-right-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - '-webkit-box-shadow': { - 'cssExtra': c[ 1 ], - 'cssAlternates': [ 'boxShadow' ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] - }, - 'azimuth': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 6 ], L[ 30 ], L[ 42 ], L[ 47 ] ] - }, - 'background': { - 'cssExtra': RegExp('^ *(?:\\s*' + s[ 0 ] + '){0,2} *$', 'i'), - 'cssPropBits': 23, - 'cssLitGroup': [ L[ 0 ], L[ 14 ], L[ 17 ], L[ 24 ], L[ 30 ], L[ 35 ], - L[ 36 ], L[ 38 ], L[ 42 ], L[ 45 ], L[ 47 ], L[ 51 ], L[ 54 ], L[ 57 - ], L[ 58 ], L[ 62 ] ] - }, - 'background-attachment': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 35 ], L[ 45 ], L[ 51 ], L[ 58 ] ] - }, - 'background-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 130, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] - }, - 'background-image': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 35 ], L[ 54 ] ] - }, - 'background-position': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 24 ], L[ 30 ], L[ 35 ], L[ 42 ] ] - }, - 'background-repeat': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 17 ], L[ 35 ], L[ 57 ] ] - }, - 'border': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 52 ], L[ 54 ], L[ 62 ] ] - }, - 'border-bottom': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 52 ], L[ 54 ], L[ 62 ] ] - }, - 'border-bottom-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] - }, - 'border-bottom-left-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - 'border-bottom-right-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - 'border-bottom-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - 'border-bottom-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - 'border-collapse': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 44 ], L[ 47 ], L[ 59 ] ] - }, - 'border-color': { - 'cssExtra': RegExp('^ *(?:\\s*' + s[ 0 ] + '){1,4} *$', 'i'), - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] - }, - 'border-left': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 52 ], L[ 54 ], L[ 62 ] ] - }, - 'border-left-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] - }, - 'border-left-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - 'border-left-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - 'border-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 36 ] ] - }, - 'border-right': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 52 ], L[ 54 ], L[ 62 ] ] - }, - 'border-right-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] - }, - 'border-right-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - 'border-right-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - 'border-spacing': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'border-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - 'border-top': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 52 ], L[ 54 ], L[ 62 ] ] - }, - 'border-top-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] - }, - 'border-top-left-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - 'border-top-right-radius': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5 - }, - 'border-top-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - 'border-top-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - 'border-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - 'bottom': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'box-shadow': { - 'cssExtra': c[ 1 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] - }, - 'caption-side': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 24 ], L[ 47 ] ] - }, - 'clear': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 30 ], L[ 40 ], L[ 47 ], L[ 54 ] ] - }, - 'clip': { - 'cssExtra': - /^ *\s*rect\(\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto)\s*,\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto)\s*,\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto)\s*,\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto) *\) *$/i, - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 130, - 'cssLitGroup': [ L[ 0 ], L[ 47 ] ] - }, - 'content': { 'cssPropBits': 0 }, - 'counter-increment': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'counter-reset': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'cue': { - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'cue-after': { - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'cue-before': { - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'cursor': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 144, - 'cssLitGroup': [ L[ 1 ], L[ 35 ], L[ 38 ], L[ 47 ] ] - }, - 'direction': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 31 ], L[ 47 ] ] - }, - 'display': { - 'cssPropBits': 32, - 'cssLitGroup': [ L[ 2 ], L[ 47 ], L[ 54 ] ] - }, - 'elevation': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 13 ], L[ 47 ] ] - }, - 'empty-cells': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 27 ], L[ 47 ] ] - }, - 'filter': { - 'cssExtra': - /^ *(?:\s*alpha\(\s*opacity\s*=\s*(?:0|\d+(?:\.\d+)?%|[+\-]?\d+(?:\.\d+)?) *\))+ *$/i, - 'cssPropBits': 32 - }, - 'float': { - 'cssAlternates': [ 'cssFloat', 'styleFloat' ], - 'cssPropBits': 32, - 'cssLitGroup': [ L[ 30 ], L[ 47 ], L[ 54 ] ] - }, - 'font': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 9, - 'cssLitGroup': [ L[ 4 ], L[ 7 ], L[ 11 ], L[ 15 ], L[ 29 ], L[ 35 ], L[ - 36 ], L[ 47 ], L[ 52 ], L[ 55 ], L[ 60 ] ] - }, - 'font-family': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 8, - 'cssLitGroup': [ L[ 15 ], L[ 35 ], L[ 47 ] ] - }, - 'font-size': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 7 ], L[ 47 ], L[ 52 ] ] - }, - 'font-stretch': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 5 ], L[ 55 ] ] - }, - 'font-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 29 ], L[ 47 ], L[ 55 ] ] - }, - 'font-variant': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 47 ], L[ 55 ], L[ 60 ] ] - }, - 'font-weight': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 4 ], L[ 47 ], L[ 55 ] ], - // ##### BEGIN: MODIFIED BY SAP - 'cssLitNumeric': true - // ##### END: MODIFIED BY SAP - }, - 'height': { - 'cssPropBits': 37, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'left': { - 'cssPropBits': 37, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'letter-spacing': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ], L[ 55 ] ] - }, - 'line-height': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 47 ], L[ 55 ] ] - }, - 'list-style': { - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 3 ], L[ 28 ], L[ 47 ], L[ 54 ] ] - }, - 'list-style-image': { - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'list-style-position': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 28 ], L[ 47 ] ] - }, - 'list-style-type': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 3 ], L[ 47 ], L[ 54 ] ] - }, - 'margin': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'margin-bottom': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'margin-left': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'margin-right': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'margin-top': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'max-height': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 38 ], L[ 47 ], L[ 54 ] ] - }, - 'max-width': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 38 ], L[ 47 ], L[ 54 ] ] - }, - 'min-height': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'min-width': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'opacity': { - 'cssPropBits': 33, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'outline': { - 'cssExtra': c[ 3 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ - 49 ], L[ 52 ], L[ 54 ] ] - }, - 'outline-color': { - 'cssExtra': c[ 2 ], - 'cssPropBits': 2, - 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 49 ] ] - }, - 'outline-style': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] - }, - 'outline-width': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] - }, - 'overflow': { - 'cssPropBits': 32, - 'cssLitGroup': [ L[ 38 ], L[ 46 ], L[ 47 ], L[ 58 ], L[ 63 ] ] - }, - 'overflow-x': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 32 ], L[ 38 ], L[ 46 ], L[ 58 ], L[ 63 ] ] - }, - 'overflow-y': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 32 ], L[ 38 ], L[ 46 ], L[ 58 ], L[ 63 ] ] - }, - 'padding': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'padding-bottom': { - 'cssPropBits': 33, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'padding-left': { - 'cssPropBits': 33, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'padding-right': { - 'cssPropBits': 33, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'padding-top': { - 'cssPropBits': 33, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'page-break-after': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 30 ], L[ 37 ], L[ 38 ], L[ 39 ], L[ 47 ] ] - }, - 'page-break-before': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 30 ], L[ 37 ], L[ 38 ], L[ 39 ], L[ 47 ] ] - }, - 'page-break-inside': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 38 ], L[ 39 ], L[ 47 ] ] - }, - 'pause': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'pause-after': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'pause-before': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'pitch': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 19 ], L[ 47 ], L[ 52 ] ] - }, - 'pitch-range': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'play-during': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 16, - 'cssLitGroup': [ L[ 38 ], L[ 47 ], L[ 53 ], L[ 54 ], L[ 57 ] ] - }, - 'position': { - 'cssPropBits': 32, - 'cssLitGroup': [ L[ 20 ], L[ 47 ] ] - }, - 'quotes': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] - }, - 'richness': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'right': { - 'cssPropBits': 37, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'speak': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 47 ], L[ 54 ], L[ 55 ], L[ 61 ] ] - }, - 'speak-header': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 37 ], L[ 47 ], L[ 56 ] ] - }, - 'speak-numeral': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 26 ], L[ 47 ] ] - }, - 'speak-punctuation': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 43 ], L[ 47 ], L[ 54 ] ] - }, - 'speech-rate': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 12 ], L[ 47 ], L[ 52 ] ] - }, - 'stress': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'table-layout': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 38 ], L[ 45 ], L[ 47 ] ] - }, - 'text-align': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 30 ], L[ 42 ], L[ 47 ], L[ 50 ] ] - }, - 'text-decoration': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 18 ], L[ 47 ], L[ 54 ] ] - }, - 'text-indent': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ] ] - }, - 'text-overflow': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 25 ] ] - }, - 'text-shadow': { - 'cssExtra': c[ 1 ], - 'cssPropBits': 7, - 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] - }, - 'text-transform': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 21 ], L[ 47 ], L[ 54 ] ] - }, - 'text-wrap': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 33 ], L[ 54 ], L[ 55 ] ] - }, - 'top': { - 'cssPropBits': 37, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'unicode-bidi': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 23 ], L[ 47 ], L[ 55 ] ] - }, - 'vertical-align': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 10 ], L[ 24 ], L[ 47 ] ] - }, - 'visibility': { - 'cssPropBits': 32, - 'cssLitGroup': [ L[ 44 ], L[ 46 ], L[ 47 ], L[ 63 ] ] - }, - 'voice-family': { - 'cssExtra': c[ 0 ], - 'cssPropBits': 8, - 'cssLitGroup': [ L[ 22 ], L[ 35 ], L[ 47 ] ] - }, - 'volume': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 16 ], L[ 47 ], L[ 52 ] ] - }, - 'white-space': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 8 ], L[ 47 ], L[ 55 ] ] - }, - 'width': { - 'cssPropBits': 33, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'word-spacing': { - 'cssPropBits': 5, - 'cssLitGroup': [ L[ 47 ], L[ 55 ] ] - }, - 'word-wrap': { - 'cssPropBits': 0, - 'cssLitGroup': [ L[ 41 ], L[ 55 ] ] - }, - 'z-index': { - 'cssPropBits': 69, - 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] - }, - 'zoom': { - 'cssPropBits': 1, - 'cssLitGroup': [ L[ 55 ] ] - } - }; - })(); - if (typeof window !== 'undefined') { - window['cssSchema'] = cssSchema; - } - // Copyright (C) 2011 Google Inc. - // - // 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. + const e$d={packageName:"@ui5/webcomponents-base",fileName:"OverrideFontFace.css",content:"@font-face{font-family:'72override';unicode-range:U+0102-0103,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EB7,U+1EB8-1EC7,U+1EC8-1ECB,U+1ECC-1EE3,U+1EE4-1EF1,U+1EF4-1EF7;src:local('Arial'),local('Helvetica'),local('sans-serif')}"}; - /** - * A lexical scannar for CSS3 as defined at http://www.w3.org/TR/css3-syntax . - * - * @author Mike Samuel - * \@provides lexCss, decodeCss - * \@overrides window - */ + let o$d;i$l(()=>{o$d=void 0;});const a$a=()=>(o$d===void 0&&(o$d=b$6()),o$d); - var lexCss; - var decodeCss; + const i$d=()=>{const t=m$d("OpenUI5Support");(!t||!t.isOpenUI5Detected())&&p$6(),c$e();},p$6=()=>{const t=document.querySelector("head>style[data-ui5-font-face]");!a$a()||t||S$5("data-ui5-font-face")||u$a(o$e,"data-ui5-font-face");},c$e=()=>{S$5("data-ui5-font-face-override")||u$a(e$d,"data-ui5-font-face-override");}; - (function () { + const t$c={packageName:"@ui5/webcomponents-base",fileName:"SystemCSSVars.css",content:":root{--_ui5_content_density:cozy}.sapUiSizeCompact,.ui5-content-density-compact,[data-ui5-compact-size]{--_ui5_content_density:compact}"}; - /** - * Decodes an escape sequence as specified in CSS3 section 4.1. - * http://www.w3.org/TR/css3-syntax/#characters - * @private - */ - function decodeCssEscape(s) { - var i = parseInt(s.substring(1), 16); - // If parseInt didn't find a hex diigt, it returns NaN so return the - // escaped character. - // Otherwise, parseInt will stop at the first non-hex digit so there's no - // need to worry about trailing whitespace. - if (i > 0xffff) { - // A supplemental codepoint. - return i -= 0x10000, - String.fromCharCode( - 0xd800 + (i >> 10), - 0xdc00 + (i & 0x3FF)); - } else if (i == i) { - return String.fromCharCode(i); - } else if (s[1] < ' ') { - // "a backslash followed by a newline is ignored". - return ''; - } else { - return s[1]; - } - } + const e$c=()=>{S$5("data-ui5-system-css-vars")||u$a(t$c,"data-ui5-system-css-vars");}; - /** - * Returns an equivalent CSS string literal given plain text: foo -> "foo". - * @private - */ - function escapeCssString(s, replacer) { - return '"' + s.replace(/[\u0000-\u001f\\\"<>]/g, replacer) + '"'; - } + const t$b=typeof document>"u",e$b={get userAgent(){return t$b?"":navigator.userAgent},get touch(){return t$b?!1:"ontouchstart"in window||navigator.maxTouchPoints>0},get chrome(){return t$b?!1:/(Chrome|CriOS)/.test(e$b.userAgent)},get firefox(){return t$b?!1:/Firefox/.test(e$b.userAgent)},get safari(){return t$b?!1:!e$b.chrome&&/(Version|PhantomJS)\/(\d+\.\d+).*Safari/.test(e$b.userAgent)},get webkit(){return t$b?!1:/webkit/.test(e$b.userAgent)},get windows(){return t$b?!1:navigator.platform.indexOf("Win")!==-1},get macOS(){return t$b?!1:!!navigator.userAgent.match(/Macintosh|Mac OS X/i)},get iOS(){return t$b?!1:!!navigator.platform.match(/iPhone|iPad|iPod/)||!!(e$b.userAgent.match(/Mac/)&&"ontouchend"in document)},get android(){return t$b?!1:!e$b.windows&&/Android/.test(e$b.userAgent)},get androidPhone(){return t$b?!1:e$b.android&&/(?=android)(?=.*mobile)/i.test(e$b.userAgent)},get ipad(){return t$b?!1:/ipad/i.test(e$b.userAgent)||/Macintosh/i.test(e$b.userAgent)&&"ontouchend"in document},_isPhone(){return u$7(),e$b.touch&&!r$d}};let o$c,i$c,r$d;const s$e=()=>{if(t$b||!e$b.windows)return !1;if(o$c===void 0){const n=e$b.userAgent.match(/Windows NT (\d+).(\d)/);o$c=n?parseFloat(n[1]):0;}return o$c>=8},c$d=()=>{if(t$b||!e$b.webkit)return !1;if(i$c===void 0){const n=e$b.userAgent.match(/(webkit)[ /]([\w.]+)/);i$c=n?parseFloat(n[1]):0;}return i$c>=537.1},u$7=()=>{if(t$b)return !1;if(r$d===void 0){if(e$b.ipad){r$d=!0;return}if(e$b.touch){if(s$e()){r$d=!0;return}if(e$b.chrome&&e$b.android){r$d=!/Mobile Safari\/[.0-9]+/.test(e$b.userAgent);return}let n=window.devicePixelRatio?window.devicePixelRatio:1;e$b.android&&c$d()&&(n=1),r$d=Math.min(window.screen.width/n,window.screen.height/n)>=600;return}r$d=e$b.userAgent.indexOf("Touch")!==-1||e$b.android&&!e$b.androidPhone;}},h$2=()=>e$b.safari,a$9=()=>(u$7(),(e$b.touch||s$e())&&r$d),d$5=()=>e$b._isPhone(),f$8=()=>t$b?!1:!a$9()&&!d$5()||s$e(),w$3=()=>e$b.iOS; - /** - * Maps chars to CSS escaped equivalents: "\n" -> "\\a ". - * @private - */ - function escapeCssStrChar(ch) { - return cssStrChars[ch] - || (cssStrChars[ch] = '\\' + ch.charCodeAt(0).toString(16) + ' '); - } + let t$a=!1;const i$b=()=>{h$2()&&w$3()&&!t$a&&(document.body.addEventListener("touchstart",()=>{}),t$a=!0);}; - /** - * Maps chars to URI escaped equivalents: "\n" -> "%0a". - * @private - */ - function escapeCssUrlChar(ch) { - return cssUrlChars[ch] - || (cssUrlChars[ch] = (ch < '\x10' ? '%0' : '%') - + ch.charCodeAt(0).toString(16)); - } + let o$b=!1,r$c;const p$5=new i$n,l$e=async()=>{if(r$c!==void 0)return r$c;const e=async n=>{if(x$1(),typeof document>"u"){n();return}n$g(b$4);const t=m$d("OpenUI5Support"),f=t?t.isOpenUI5Detected():!1,s=m$d("F6Navigation");t&&await t.init(),s&&!f&&s.init(),await d$6(),await I$3(r$b()),t&&t.attachListeners(),i$d(),e$c(),i$b(),n(),o$b=!0,p$5.fireEvent("boot");};return r$c=new Promise(e),r$c},b$4=e=>{o$b&&e===r$b()&&I$3(r$b());}; - /** - * Mapping of CSS special characters to escaped equivalents. - * @private - */ - var cssStrChars = { - '\\': '\\\\' - }; + let t$9;i$l(()=>{t$9=void 0;});const r$b=()=>(t$9===void 0&&(t$9=T$1()),t$9),i$a=()=>{const e=r$b();return y$3(e)?!e.startsWith("sap_horizon"):!m$7()?.baseThemeName?.startsWith("sap_horizon")},y$3=e=>s$p.includes(e); - /** - * Mapping of CSS special characters to URL-escaped equivalents. - * @private - */ - var cssUrlChars = { - '\\': '%5c' - }; + var t$8=(o=>(o.SAPIconsV4="SAP-icons-v4",o.SAPIconsV5="SAP-icons-v5",o.SAPIconsTNTV2="tnt-v2",o.SAPIconsTNTV3="tnt-v3",o.SAPBSIconsV1="business-suite-v1",o.SAPBSIconsV2="business-suite-v2",o))(t$8||{});const s$d=new Map;s$d.set("SAP-icons",{legacy:"SAP-icons-v4",sap_horizon:"SAP-icons-v5"}),s$d.set("tnt",{legacy:"tnt-v2",sap_horizon:"tnt-v3"}),s$d.set("business-suite",{legacy:"business-suite-v1",sap_horizon:"business-suite-v2"});const c$c=(n,e)=>{if(s$d.has(n)){s$d.set(n,{...e,...s$d.get(n)});return}s$d.set(n,e);},r$a=n=>{const e=i$a()?"legacy":"sap_horizon";return s$d.has(n)?s$d.get(n)[e]:n}; - // The comments below are copied from the CSS3 module syntax at - // http://www.w3.org/TR/css3-syntax . - // These string constants minify out when this is run-through closure - // compiler. - // Rules that have been adapted have comments prefixed with "Diff:", and - // where rules have been combined to avoid back-tracking in the regex engine - // or to work around limitations, there is a comment prefixed with - // "NewRule:". - - // In the below, we assume CRLF and CR have been normalize to CR. - - // wc ::= #x9 | #xA | #xC | #xD | #x20 - var WC = '[\\t\\n\\f ]'; - // w ::= wc* - var W = WC + '*'; - // nl ::= #xA | #xD #xA | #xD | #xC - var NL = '[\\n\\f]'; - // nonascii ::= [#x80-#xD7FF#xE000-#xFFFD#x10000-#x10FFFF] - // NewRule: Supplemental codepoints are represented as surrogate pairs in JS. - var SURROGATE_PAIR = '[\\ud800-\\udbff][\\udc00-\\udfff]'; - var NONASCII = '[\\u0080-\\ud7ff\\ue000-\\ufffd]|' + SURROGATE_PAIR; - // unicode ::= '\' [0-9a-fA-F]{1,6} wc? - // NewRule: No point in having ESCAPE do (\\x|\\y) - var UNICODE_TAIL = '[0-9a-fA-F]{1,6}' + WC + '?'; - // escape ::= unicode - // | '\' [#x20-#x7E#x80-#xD7FF#xE000-#xFFFD#x10000-#x10FFFF] - // NewRule: Below we use escape tail to efficiently match an escape or a - // line continuation so we can decode string content. - var ESCAPE_TAIL = '(?:' + UNICODE_TAIL - + '|[\\u0020-\\u007e\\u0080-\\ud7ff\\ue000\\ufffd]|' - + SURROGATE_PAIR + ')'; - var ESCAPE = '\\\\' + ESCAPE_TAIL; - // urlchar ::= [#x9#x21#x23-#x26#x28-#x7E] | nonascii | escape - var URLCHAR = '(?:[\\t\\x21\\x23-\\x26\\x28-\\x5b\\x5d-\\x7e]|' - + NONASCII + '|' + ESCAPE + ')'; - // stringchar ::= urlchar | #x20 | '\' nl - // We ignore mismatched surrogate pairs inside strings, so stringchar - // simplifies to a non-(quote|newline|backslash) or backslash any. - // Since we normalize CRLF to a single code-unit, there is no special - // handling needed for '\\' + CRLF. - var STRINGCHAR = '[^\'"\\n\\f\\\\]|\\\\[\\s\\S]'; - // string ::= '"' (stringchar | "'")* '"' | "'" (stringchar | '"')* "'" - var STRING = '"(?:\'|' + STRINGCHAR + ')*"' - + '|\'(?:\"|' + STRINGCHAR + ')*\''; - // num ::= [0-9]+ | [0-9]* '.' [0-9]+ - // Diff: We attach signs to num tokens. - var NUM = '[-+]?(?:[0-9]+(?:[.][0-9]+)?|[.][0-9]+)'; - // nmstart ::= [a-zA-Z] | '_' | nonascii | escape - var NMSTART = '(?:[a-zA-Z_]|' + NONASCII + '|' + ESCAPE + ')'; - // nmchar ::= [a-zA-Z0-9] | '-' | '_' | nonascii | escape - var NMCHAR = '(?:[a-zA-Z0-9_-]|' + NONASCII + '|' + ESCAPE + ')'; - // ident ::= '-'? nmstart nmchar* - var IDENT = '-?' + NMSTART + NMCHAR + '*'; - - // NewRule: union of IDENT, ATKEYWORD, HASH, but excluding #[0-9]. - var WORD_TERM = '(?:@?-?' + NMSTART + '|#)' + NMCHAR + '*'; - var NUMERIC_VALUE = NUM + '(?:%|' + IDENT + ')?'; - // URI ::= "url(" w (string | urlchar* ) w ")" - var URI = 'url[(]' + W + '(?:' + STRING + '|' + URLCHAR + '*)' + W + '[)]'; - // UNICODE-RANGE ::= "U+" [0-9A-F?]{1,6} ('-' [0-9A-F]{1,6})? - var UNICODE_RANGE = 'U[+][0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?'; - // CDO ::= "<\!--" - var CDO = '<\!--'; - // CDC ::= "-->" - var CDC = '-->'; - // S ::= wc+ - var S = WC + '+'; - // COMMENT ::= "/*" [^*]* '*'+ ([^/] [^*]* '*'+)* "/" - // Diff: recognizes // comments. - var COMMENT = '/(?:[*][^*]*[*]+(?:[^/][^*]*[*]+)*/|/[^\\n\\f]*)'; - // FUNCTION ::= ident '(' - // Diff: We exclude url explicitly. - // TODO: should we be tolerant of "fn ("? - // ##### BEGIN: MODIFIED BY SAP - // Avoid risk of 'catastrophic backtracking' when unicode escapes are used - // var FUNCTION = '(?!url[(])' + IDENT + '[(]'; - var FUNCTION = '(?!url[(])(?=(' + IDENT + '))\\1[(]'; - // NewRule: one rule for all the comparison operators. - var CMP_OPS = '[~|^$*]='; - // CHAR ::= any character not matched by the above rules, except for " or ' - // Diff: We exclude / and \ since they are handled above to prevent - // /* without a following */ from combining when comments are concatenated. - var CHAR = '[^"\'\\\\/]|/(?![/*])'; - // BOM ::= #xFEFF - var BOM = '\\uFEFF'; - - var CSS_TOKEN = new RegExp([ - BOM, UNICODE_RANGE, URI, FUNCTION, WORD_TERM, STRING, NUMERIC_VALUE, - CDO, CDC, S, COMMENT, CMP_OPS, CHAR].join("|"), 'gi'); + var t$7=(s=>(s["SAP-icons"]="SAP-icons-v4",s.horizon="SAP-icons-v5",s["SAP-icons-TNT"]="tnt",s.BusinessSuiteInAppSymbols="business-suite",s))(t$7||{});const n$e=e=>t$7[e]?t$7[e]:e; - /** - * Decodes CSS escape sequences in a CSS string body. - */ - decodeCss = function (css) { - return css.replace( - new RegExp('\\\\(?:' + ESCAPE_TAIL + '|' + NL + ')', 'g'), - decodeCssEscape); - }; + const i$9=o=>{const t=c$i(r$b());return !o&&t?n$e(t):o?r$a(o):r$a("SAP-icons")}; - /** - * Given CSS Text, returns an array of normalized tokens. - * @param {string} cssText - * @return {Array.} tokens where all ignorable token sequences have - * been reduced to a single {@code " "} and all strings and - * {@code url(...)} tokens have been normalized to use double quotes as - * delimiters and to not otherwise contain double quotes. - */ - lexCss = function (cssText) { - cssText = '' + cssText; - var tokens = cssText.replace(/\r\n?/g, '\n') // Normalize CRLF & CR to LF. - .match(CSS_TOKEN) || []; - var j = 0; - var last = ' '; - for (var i = 0, n = tokens.length; i < n; ++i) { - // Normalize all escape sequences. We will have to re-escape some - // codepoints in string and url(...) bodies but we already know the - // boundaries. - // We might mistakenly treat a malformed identifier like \22\20\22 as a - // string, but that will not break any valid stylesheets since we requote - // and re-escape in string below. - var tok = decodeCss(tokens[i]); - var len = tok.length; - var cc = tok.charCodeAt(0); - tok = - // All strings should be double quoted, and the body should never - // contain a double quote. - (cc == '"'.charCodeAt(0) || cc == '\''.charCodeAt(0)) - ? escapeCssString(tok.substring(1, len - 1), escapeCssStrChar) - // A breaking ignorable token should is replaced with a single space. - : (cc == '/'.charCodeAt(0) && len > 1 // Comment. - || tok == '\\' || tok == CDC || tok == CDO || tok == '\ufeff' - // Characters in W. - || cc <= ' '.charCodeAt(0)) - ? ' ' - // Make sure that all url(...)s are double quoted. - : /url\(/i.test(tok) - ? 'url(' + escapeCssString( - tok.replace( - new RegExp('^url\\(' + W + '["\']?|["\']?' + W + '\\)$', 'gi'), - ''), - escapeCssUrlChar) - + ')' - // Escapes in identifier like tokens will have been normalized above. - : tok; - // Merge adjacent space tokens. - if (last != tok || tok != ' ') { - tokens[j++] = last = tok; - } + const e$a=new i$n,n$d="languageChange",t$6=a=>{e$a.attachEvent(n$d,a);}; + + let e$9,n$c;i$l(()=>{e$9=void 0,n$c=void 0;});const d$4=()=>(e$9===void 0&&(e$9=L$2()),e$9),c$b=()=>(n$c===void 0&&(n$c=F()),n$c); + + const c$a=["value-changed","click"];let e$8;i$l(()=>{e$8=void 0;});const s$c=t=>c$a.includes(t),l$d=t=>{const n=o$a();return !(typeof n!="boolean"&&n.events&&n.events.includes&&n.events.includes(t))},o$a=()=>(e$8===void 0&&(e$8=U$2()),e$8),a$8=t=>{const n=o$a();return s$c(t)?!1:n===!0?!0:!l$d(t)}; + + const m$6=(a={})=>e=>{if(Object.prototype.hasOwnProperty.call(e,"metadata")||(e.metadata={}),typeof a=="string"){e.metadata.tag=a;return}const{tag:f,languageAware:o,themeAware:r,cldr:s,fastNavigation:l,formAssociated:n,shadowRootOptions:d,features:i}=a;e.metadata.tag=f,o&&(e.metadata.languageAware=o),s&&(e.metadata.cldr=s),i&&(e.metadata.features=i),r&&(e.metadata.themeAware=r),l&&(e.metadata.fastNavigation=l),n&&(e.metadata.formAssociated=n),d&&(e.metadata.shadowRootOptions=d),["renderer","template","styles","dependencies"].forEach(t=>{a[t]&&Object.defineProperty(e,t,{get:()=>a[t]});});}; + + const s$b=o=>(p,r)=>{const t=p.constructor;Object.prototype.hasOwnProperty.call(t,"metadata")||(t.metadata={});const e=t.metadata;e.properties||(e.properties={});const a=e.properties;a[r]||(a[r]=o??{});}; + + const y$2={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CONTROL:17,ALT:18,BREAK:19,CAPS_LOCK:20,ESCAPE:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,ARROW_LEFT:37,ARROW_UP:38,ARROW_RIGHT:39,ARROW_DOWN:40,PRINT:44,INSERT:45,DELETE:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_4:52,DIGIT_5:53,DIGIT_6:54,DIGIT_7:55,DIGIT_8:56,DIGIT_9:57,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,WINDOWS:91,CONTEXT_MENU:93,TURN_OFF:94,SLEEP:95,NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_ASTERISK:106,NUMPAD_PLUS:107,NUMPAD_MINUS:109,NUMPAD_COMMA:110,NUMPAD_SLASH:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUM_LOCK:144,SCROLL_LOCK:145,COLON:186,PLUS:187,COMMA:188,SLASH:189,DOT:190,PIPE:191,SEMICOLON:192,MINUS:219,GREAT_ACCENT:220,EQUALS:221,SINGLE_QUOTE:222,BACKSLASH:226},b$3=o=>(o.key?o.key==="Enter":o.keyCode===y$2.ENTER)&&!a$7(o),i$8=o=>(o.key?o.key==="Spacebar"||o.key===" ":o.keyCode===y$2.SPACE)&&!a$7(o),a$7=o=>o.shiftKey||o.altKey||k$1(o),k$1=o=>!!(o.metaKey||o.ctrlKey); + + var r$9=(l=>(l.Auto="Auto",l.Vertical="Vertical",l.Horizontal="Horizontal",l.Paging="Paging",l))(r$9||{}); + + var l$c=(c=>(c.Static="Static",c.Cyclic="Cyclic",c))(l$c||{}); + + const s$a=new Map,o$9=new Map,n$b=new Map,c$9=e=>{if(!s$a.has(e)){const a=p$4(e.split("-"));s$a.set(e,a);}return s$a.get(e)},l$b=e=>{if(!o$9.has(e)){const a=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();o$9.set(e,a);}return o$9.get(e)},p$4=e=>e.map((a,t)=>t===0?a.toLowerCase():a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(""),b$2=e=>{const a=n$b.get(e);if(a)return a;const t=c$9(e),r=t.charAt(0).toUpperCase()+t.slice(1);return n$b.set(e,r),r}; + + const o$8=t=>{if(!(t instanceof HTMLElement))return "default";const e=t.getAttribute("slot");if(e){const r=e.match(/^(.+?)-\d+$/);return r?r[1]:e}return "default"},n$a=t=>t instanceof HTMLSlotElement?t.assignedNodes({flatten:!0}).filter(e=>e instanceof HTMLElement):[t],s$9=t=>t.reduce((e,r)=>e.concat(n$a(r)),[]); + + let p$3 = class p{constructor(t){this.metadata=t;}getInitialState(){if(Object.prototype.hasOwnProperty.call(this,"_initialState"))return this._initialState;const t={};if(this.slotsAreManaged()){const o=this.getSlots();for(const[e,s]of Object.entries(o)){const n=s.propertyName||e;t[n]=[],t[c$9(n)]=t[n];}}return this._initialState=t,t}static validateSlotValue(t,a){return g$4(t,a)}getPureTag(){return this.metadata.tag||""}getFeatures(){return this.metadata.features||[]}getTag(){const t=this.metadata.tag;if(!t)return "";const a=p$8(t);return a?`${t}-${a}`:t}hasAttribute(t){const a=this.getProperties()[t];return a.type!==Object&&a.type!==Array&&!a.noAttribute}getPropertiesList(){return Object.keys(this.getProperties())}getAttributesList(){return this.getPropertiesList().filter(this.hasAttribute.bind(this)).map(l$b)}canSlotText(){return this.getSlots().default?.type===Node}hasSlots(){return !!Object.entries(this.getSlots()).length}hasIndividualSlots(){return this.slotsAreManaged()&&Object.values(this.getSlots()).some(t=>t.individualSlots)}slotsAreManaged(){return !!this.metadata.managedSlots}supportsF6FastNavigation(){return !!this.metadata.fastNavigation}getProperties(){return this.metadata.properties||(this.metadata.properties={}),this.metadata.properties}getEvents(){return this.metadata.events||(this.metadata.events={}),this.metadata.events}getSlots(){return this.metadata.slots||(this.metadata.slots={}),this.metadata.slots}isLanguageAware(){return !!this.metadata.languageAware}isThemeAware(){return !!this.metadata.themeAware}needsCLDR(){return !!this.metadata.cldr}getShadowRootOptions(){return this.metadata.shadowRootOptions||{}}isFormAssociated(){return !!this.metadata.formAssociated}shouldInvalidateOnChildChange(t,a,o){const e=this.getSlots()[t].invalidateOnChildChange;if(e===void 0)return !1;if(typeof e=="boolean")return e;if(typeof e=="object"){if(a==="property"){if(e.properties===void 0)return !1;if(typeof e.properties=="boolean")return e.properties;if(Array.isArray(e.properties))return e.properties.includes(o);throw new Error("Wrong format for invalidateOnChildChange.properties: boolean or array is expected")}if(a==="slot"){if(e.slots===void 0)return !1;if(typeof e.slots=="boolean")return e.slots;if(Array.isArray(e.slots))return e.slots.includes(o);throw new Error("Wrong format for invalidateOnChildChange.slots: boolean or array is expected")}}throw new Error("Wrong format for invalidateOnChildChange: boolean or object is expected")}getI18n(){return this.metadata.i18n||(this.metadata.i18n={}),this.metadata.i18n}};const g$4=(r,t)=>(r&&n$a(r).forEach(a=>{if(!(a instanceof t.type))throw new Error(`The element is not of type ${t.type.toString()}`)}),r); + + const r$8=()=>m$c("CustomStyle.eventProvider",new i$n),n$9="CustomCSSChange",i$7=t=>{r$8().attachEvent(n$9,t);},c$8=()=>m$c("CustomStyle.customCSSFor",{});i$7(t=>{C$2({tag:t});});const l$a=t=>{const e=c$8();return e[t]?e[t].join(""):""}; + + const a$6=t=>Array.isArray(t)?t.filter(r=>!!r).flat(10).map(r=>typeof r=="string"?r:r.content).join(" "):typeof t=="string"?t:t.content; + + const e$7=new Map;i$7(t=>{e$7.delete(`${t}_normal`);});const y$1=t=>{const o=t.getMetadata().getTag(),n=`${o}_normal`,s=m$d("OpenUI5Enablement");if(!e$7.has(n)){let l="";s&&(l=a$6(s.getBusyIndicatorStyles()));const a=l$a(o)||"",m=`${a$6(t.styles)} ${a} ${l}`;e$7.set(n,m);}return e$7.get(n)}; + + const e$6=new Map;i$7(t=>{e$6.delete(`${t}_normal`);});const s$8=t=>{const n=`${t.getMetadata().getTag()}_normal`;if(!e$6.has(n)){const a=y$1(t),o=new CSSStyleSheet;o.replaceSync(a),e$6.set(n,[o]);}return e$6.get(n)}; + + const n$8=o=>{const e=o.constructor,t=o.shadowRoot,r=o.render();if(!t){console.warn("There is no shadow root to update");return}t.adoptedStyleSheets=s$8(e),e.renderer(r,t,{host:o});}; + + const r$7=[],o$7=t=>r$7.some(s=>t.startsWith(s)); + + const t$5=new WeakMap,n$7=(e,o,r)=>{const s=new MutationObserver(o);t$5.set(e,s),s.observe(e,r);},b$1=e=>{const o=t$5.get(e);o&&(o.disconnect(),t$5.delete(e));}; + + const r$6=t=>t.matches(":dir(rtl)")?"rtl":"ltr"; + + const s$7=["disabled","title","hidden","role","draggable"],r$5=e=>s$7.includes(e)||e.startsWith("aria")?!0:![HTMLElement,Element,Node].some(t=>t.prototype.hasOwnProperty(e)); + + const n$6=(t,r)=>{if(t.length!==r.length)return !1;for(let e=0;e{const t=c$7(e),o=c$h();return n.call(e,e,t,o)},c$7=n=>{const e=n.constructor,t=e.getMetadata().getPureTag(),o=e.getUniqueDependencies().map(s=>s.getMetadata().getPureTag()).filter(i$i);return i$i(t)&&o.push(t),o}; + + const o$6=t=>{s$6(t)&&e$5(t);},e$5=t=>{if(t._internals?.form){if(n$5(t),!t.name){t._internals?.setFormValue(null);return}t._internals.setFormValue(t.formFormattedValue);}},n$5=async t=>{if(t._internals?.form)if(t.formValidity&&Object.keys(t.formValidity).some(r=>r)){const r=await t.formElementAnchor?.();t._internals.setValidity(t.formValidity,t.formValidityMessage,r);}else t._internals.setValidity({});},s$6=t=>"formFormattedValue"in t&&"name"in t; + + const t$4=typeof document>"u",o$5=()=>{if(t$4)return a$e;const a=navigator.languages,n=()=>navigator.language;return a&&a[0]||n()||a$e}; + + const n$4=/^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i;let r$4 = class r{constructor(s){const t=n$4.exec(s.replace(/_/g,"-"));if(t===null)throw new Error(`The given language ${s} does not adhere to BCP-47.`);this.sLocaleId=s,this.sLanguage=t[1]||a$e,this.sScript=t[2]||"",this.sRegion=t[3]||"",this.sVariant=t[4]&&t[4].slice(1)||null,this.sExtension=t[5]&&t[5].slice(1)||null,this.sPrivateUse=t[6]||null,this.sLanguage&&(this.sLanguage=this.sLanguage.toLowerCase()),this.sScript&&(this.sScript=this.sScript.toLowerCase().replace(/^[a-z]/,i=>i.toUpperCase())),this.sRegion&&(this.sRegion=this.sRegion.toUpperCase());}getLanguage(){return this.sLanguage}getScript(){return this.sScript}getRegion(){return this.sRegion}getVariant(){return this.sVariant}getVariantSubtags(){return this.sVariant?this.sVariant.split("-"):[]}getExtension(){return this.sExtension}getExtensionSubtags(){return this.sExtension?this.sExtension.slice(2).split("-"):[]}getPrivateUse(){return this.sPrivateUse}getPrivateUseSubtags(){return this.sPrivateUse?this.sPrivateUse.slice(2).split("-"):[]}hasPrivateUseSubtag(s){return this.getPrivateUseSubtags().indexOf(s)>=0}toString(){const s=[this.sLanguage];return this.sScript&&s.push(this.sScript),this.sRegion&&s.push(this.sRegion),this.sVariant&&s.push(this.sVariant),this.sExtension&&s.push(this.sExtension),this.sPrivateUse&&s.push(this.sPrivateUse),s.join("-")}}; + + const r$3=new Map,n$3=t=>(r$3.has(t)||r$3.set(t,new r$4(t)),r$3.get(t)),c$6=t=>{try{if(t&&typeof t=="string")return n$3(t)}catch{}return new r$4(r$j)},s$5=t=>{const e=d$4();return e?n$3(e):c$6(o$5())}; + + const _$3=/^((?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3})|[A-Z]{4}|[A-Z]{5,8})(?:-([A-Z]{4}))?(?:-([A-Z]{2}|[0-9]{3}))?((?:-[0-9A-Z]{5,8}|-[0-9][0-9A-Z]{3})*)((?:-[0-9A-WYZ](?:-[0-9A-Z]{2,8})+)*)(?:-(X(?:-[0-9A-Z]{1,8})+))?$/i,c$5=/(?:^|-)(saptrc|sappsd)(?:-|$)/i,f$7={he:"iw",yi:"ji",nb:"no",sr:"sh"},p$2=i=>{let e;if(!i)return r$j;if(typeof i=="string"&&(e=_$3.exec(i.replace(/_/g,"-")))){let t=e[1].toLowerCase(),n=e[3]?e[3].toUpperCase():void 0;const s=e[2]?e[2].toLowerCase():void 0,r=e[4]?e[4].slice(1):void 0,o=e[6];return t=f$7[t]||t,o&&(e=c$5.exec(o))||r&&(e=c$5.exec(r))?`en_US_${e[1].toLowerCase()}`:(t==="zh"&&!n&&(s==="hans"?n="CN":s==="hant"&&(n="TW")),t+(n?"_"+n+(r?"_"+r.replace("-","_"):""):""))}return r$j}; + + const e$4=r=>{if(!r)return r$j;if(r==="zh_HK")return "zh_TW";const n=r.lastIndexOf("_");return n>=0?r.slice(0,n):r!==r$j?r$j:""}; + + const d$3=new Set,m$5=new Set,g$3=new Map,l$8=new Map,u$6=new Map,f$6=(n,t)=>{g$3.set(n,t);},A$3=n=>g$3.get(n),h$1=(n,t)=>{const e=`${n}/${t}`;return u$6.has(e)},B$1=(n,t)=>{const e=`${n}/${t}`,r=u$6.get(e);return r&&!l$8.get(e)&&l$8.set(e,r(t)),l$8.get(e)},M$1=n=>{d$3.has(n)||(console.warn(`[${n}]: Message bundle assets are not configured. Falling back to English texts.`,` Add \`import "${n}/dist/Assets.js"\` in your bundle and make sure your build tool supports dynamic imports and JSON imports. See section "Assets" in the documentation for more information.`),d$3.add(n));},L$1=(n,t)=>t!==a$e&&!h$1(n,t),w$2=async n=>{const t=s$5().getLanguage(),e=s$5().getRegion(),r=s$5().getVariant();let s=t+(e?`-${e}`:"")+(r?`-${r}`:"");if(L$1(n,s))for(s=p$2(s);L$1(n,s);)s=e$4(s);const I=c$b();if(s===a$e&&!I){f$6(n,null);return}if(!h$1(n,s)){M$1(n);return}try{const o=await B$1(n,s);f$6(n,o);}catch(o){const a=o;m$5.has(a.message)||(m$5.add(a.message),console.error(a.message));}};t$6(n=>{const t=[...g$3.keys()];return Promise.all(t.map(w$2))}); + + const g$2=/('')|'([^']+(?:''[^']*)*)(?:'|$)|\{([0-9]+(?:\s*,[^{}]*)?)\}|[{}]/g,i$6=(n,t)=>(t=t||[],n.replace(g$2,(p,s,e,r,o)=>{if(s)return "'";if(e)return e.replace(/''/g,"'");if(r){const a=typeof r=="string"?parseInt(r):r;return String(t[a])}throw new Error(`[i18n]: pattern syntax error at pos ${o}`)})); + + const r$2=new Map;let u$5 = class u{constructor(e){this.packageName=e;}getText(e,...i){if(typeof e=="string"&&(e={key:e,defaultText:e}),!e||!e.key)return "";const t=A$3(this.packageName);t&&!t[e.key]&&console.warn(`Key ${e.key} not found in the i18n bundle, the default text will be used`);const l=t&&t[e.key]?t[e.key]:e.defaultText||e.key;return i$6(l,i)}};const a$5=n=>{if(r$2.has(n))return r$2.get(n);const e=new u$5(n);return r$2.set(n,e),e},f$5=async n=>(await w$2(n),a$5(n)); + + const f$4=new Map,s$4=new Map,i$5=new Map,D$1=new Set;let d$2=!1;const O$1={iw:"he",ji:"yi",in:"id"},l$7=t=>{d$2||(console.warn(`[LocaleData] Supported locale "${t}" not configured, import the "Assets.js" module from the webcomponents package you are using.`),d$2=!0);},R$1=(t,e,n)=>{t=t&&O$1[t]||t,t==="no"&&(t="nb"),t==="zh"&&!e&&(n==="Hans"?e="CN":n==="Hant"&&(e="TW")),(t==="sh"||t==="sr"&&n==="Latn")&&(t="sr",e="Latn");let r=`${t}_${e}`;return n$k.includes(r)?s$4.has(r)?r:(l$7(r),r$j):(r=t,n$k.includes(r)?s$4.has(r)?r:(l$7(r),r$j):r$j)},m$4=(t,e)=>{f$4.set(t,e);},_$2=t=>{if(!i$5.get(t)){const e=s$4.get(t);if(!e)throw new Error(`CLDR data for locale ${t} is not loaded!`);i$5.set(t,e(t));}return i$5.get(t)},u$4=async(t,e,n)=>{const r=R$1(t,e,n),p=m$d("OpenUI5Support");if(p){const o=p.getLocaleDataObject();if(o){m$4(r,o);return}}try{const o=await _$2(r);m$4(r,o);}catch(o){const c=o;D$1.has(c.message)||(D$1.add(c.message),console.error(c.message));}},C$1=(t,e)=>{s$4.set(t,e);};C$1("en",async()=>(await fetch("https://sdk.openui5.org/1.120.17/resources/sap/ui/core/cldr/en.json")).json()),t$6(()=>{const t=s$5();return u$4(t.getLanguage(),t.getRegion(),t.getScript())}); + + let it=0;const A$2=new Map,I$2=new Map,O={fromAttribute(d,u){return u===Boolean?d!==null:u===Number?d===null?void 0:parseFloat(d):d},toAttribute(d,u){return u===Boolean?d?"":null:u===Object||u===Array||d==null?null:String(d)}};function v$1(d){this._suppressInvalidation||(this.onInvalidation(d),this._changedState.push(d),l$g(this),this._invalidationEventProvider.fireEvent("invalidate",{...d,target:this}));}function at(d,u){do{const t=Object.getOwnPropertyDescriptor(d,u);if(t)return t;d=Object.getPrototypeOf(d);}while(d&&d!==HTMLElement.prototype)}let S$2 = class S extends HTMLElement{constructor(){super();this._rendered=!1;const t=this.constructor;this._changedState=[],this._suppressInvalidation=!0,this._inDOM=!1,this._fullyConnected=!1,this._childChangeListeners=new Map,this._slotChangeListeners=new Map,this._invalidationEventProvider=new i$n,this._componentStateFinalizedEventProvider=new i$n;let e;this._domRefReadyPromise=new Promise(n=>{e=n;}),this._domRefReadyPromise._deferredResolve=e,this._doNotSyncAttributes=new Set,this._slotsAssignedNodes=new WeakMap,this._state={...t.getMetadata().getInitialState()},this.initializedProperties=new Map,this.constructor.getMetadata().getPropertiesList().forEach(n=>{if(this.hasOwnProperty(n)){const o=this[n];this.initializedProperties.set(n,o);}}),this._internals=this.attachInternals(),this._initShadowRoot();}_initShadowRoot(){const t=this.constructor;if(t._needsShadowDOM()){const e={mode:"open"};this.attachShadow({...e,...t.getMetadata().getShadowRootOptions()}),t.getMetadata().slotsAreManaged()&&this.shadowRoot.addEventListener("slotchange",this._onShadowRootSlotChange.bind(this));}}_onShadowRootSlotChange(t){t.target?.getRootNode()===this.shadowRoot&&this._processChildren();}get _id(){return this.__id||(this.__id=`ui5wc_${++it}`),this.__id}render(){const t=this.constructor.template;return l$9(t,this)}async connectedCallback(){const t=this.constructor;this.setAttribute(t.getMetadata().getPureTag(),""),t.getMetadata().supportsF6FastNavigation()&&this.setAttribute("data-sap-ui-fastnavgroup","true");const e=t.getMetadata().slotsAreManaged();this._inDOM=!0,e&&(this._startObservingDOMChildren(),await this._processChildren()),this._inDOM&&(t.asyncFinished||await t.definePromise,c$f(this),this._domRefReadyPromise._deferredResolve(),this._fullyConnected=!0,this.onEnterDOM());}disconnectedCallback(){const e=this.constructor.getMetadata().slotsAreManaged();this._inDOM=!1,e&&this._stopObservingDOMChildren(),this._fullyConnected&&(this.onExitDOM(),this._fullyConnected=!1),this._domRefReadyPromise._deferredResolve(),h$4(this);}onBeforeRendering(){}onAfterRendering(){}onEnterDOM(){}onExitDOM(){}_startObservingDOMChildren(){const e=this.constructor.getMetadata();if(!e.hasSlots())return;const n=e.canSlotText(),o={childList:!0,subtree:n,characterData:n};n$7(this,this._processChildren.bind(this),o);}_stopObservingDOMChildren(){b$1(this);}async _processChildren(){this.constructor.getMetadata().hasSlots()&&await this._updateSlots();}async _updateSlots(){const t=this.constructor,e=t.getMetadata().getSlots(),s=t.getMetadata().canSlotText(),n=Array.from(s?this.childNodes:this.children),o=new Map,i=new Map;for(const[l,f]of Object.entries(e)){const c=f.propertyName||l;i.set(c,l),o.set(c,[...this._state[c]]),this._clearSlot(l,f);}const r=new Map,a=new Map,h=n.map(async(l,f)=>{const c=o$8(l),g=e[c];if(g===void 0){if(c!=="default"){const p=Object.keys(e).join(", ");console.warn(`Unknown slotName: ${c}, ignoring`,l,`Valid values are: ${p}`);}return}if(g.individualSlots){const p=(r.get(c)||0)+1;r.set(c,p),l._individualSlot=`${c}-${p}`;}if(l instanceof HTMLElement){const p=l.localName;if(p.includes("-")&&!o$7(p)){if(!customElements.get(p)){const T=customElements.whenDefined(p);let E=A$2.get(p);E||(E=new Promise(U=>setTimeout(U,1e3)),A$2.set(p,E)),await Promise.race([T,E]);}customElements.upgrade(l);}}if(l=t.getMetadata().constructor.validateSlotValue(l,g),_$1(l)&&g.invalidateOnChildChange){const p=this._getChildChangeListener(c);l.attachInvalidate.call(l,p);}l instanceof HTMLSlotElement&&this._attachSlotChange(l,c,!!g.invalidateOnChildChange);const C=g.propertyName||c;a.has(C)?a.get(C).push({child:l,idx:f}):a.set(C,[{child:l,idx:f}]);});await Promise.all(h),a.forEach((l,f)=>{this._state[f]=l.sort((c,g)=>c.idx-g.idx).map(c=>c.child),this._state[c$9(f)]=this._state[f];});let m=!1;for(const[l,f]of Object.entries(e)){const c=f.propertyName||l;n$6(o.get(c),this._state[c])||(v$1.call(this,{type:"slot",name:i.get(c),reason:"children"}),m=!0,t.getMetadata().isFormAssociated()&&e$5(this));}m||v$1.call(this,{type:"slot",name:"default",reason:"textcontent"});}_clearSlot(t,e){const s=e.propertyName||t;this._state[s].forEach(o=>{if(_$1(o)){const i=this._getChildChangeListener(t);o.detachInvalidate.call(o,i);}o instanceof HTMLSlotElement&&this._detachSlotChange(o,t);}),this._state[s]=[],this._state[c$9(s)]=this._state[s];}attachInvalidate(t){this._invalidationEventProvider.attachEvent("invalidate",t);}detachInvalidate(t){this._invalidationEventProvider.detachEvent("invalidate",t);}_onChildChange(t,e){this.constructor.getMetadata().shouldInvalidateOnChildChange(t,e.type,e.name)&&v$1.call(this,{type:"slot",name:t,reason:"childchange",child:e.target});}attributeChangedCallback(t,e,s){let n;if(this._doNotSyncAttributes.has(t))return;const o=this.constructor.getMetadata().getProperties(),i=t.replace(/^ui5-/,""),r=c$9(i);if(o.hasOwnProperty(r)){const a=o[r];n=(a.converter??O).fromAttribute(s,a.type),this[r]=n;}}formAssociatedCallback(){this.constructor.getMetadata().isFormAssociated()&&o$6(this);}static get formAssociated(){return this.getMetadata().isFormAssociated()}_updateAttribute(t,e){const s=this.constructor;if(!s.getMetadata().hasAttribute(t))return;const o=s.getMetadata().getProperties()[t],i=l$b(t),a=(o.converter||O).toAttribute(e,o.type);this._doNotSyncAttributes.add(i),a==null?this.removeAttribute(i):this.setAttribute(i,a),this._doNotSyncAttributes.delete(i);}_getChildChangeListener(t){return this._childChangeListeners.has(t)||this._childChangeListeners.set(t,this._onChildChange.bind(this,t)),this._childChangeListeners.get(t)}_getSlotChangeListener(t){return this._slotChangeListeners.has(t)||this._slotChangeListeners.set(t,this._onSlotChange.bind(this,t)),this._slotChangeListeners.get(t)}_attachSlotChange(t,e,s){const n=this._getSlotChangeListener(e);t.addEventListener("slotchange",o=>{if(n.call(t,o),s){const i=this._slotsAssignedNodes.get(t);i&&i.forEach(a=>{if(_$1(a)){const h=this._getChildChangeListener(e);a.detachInvalidate.call(a,h);}});const r=s$9([t]);this._slotsAssignedNodes.set(t,r),r.forEach(a=>{if(_$1(a)){const h=this._getChildChangeListener(e);a.attachInvalidate.call(a,h);}});}});}_detachSlotChange(t,e){t.removeEventListener("slotchange",this._getSlotChangeListener(e));}_onSlotChange(t){v$1.call(this,{type:"slot",name:t,reason:"slotchange"});}onInvalidation(t){}updateAttributes(){const e=this.constructor.getMetadata().getProperties();for(const[s,n]of Object.entries(e))this._updateAttribute(s,this[s]);}_render(){const t=this.constructor,e=t.getMetadata().hasIndividualSlots();this.initializedProperties.size>0&&(Array.from(this.initializedProperties.entries()).forEach(([s,n])=>{delete this[s],this[s]=n;}),this.initializedProperties.clear()),this._suppressInvalidation=!0;try{this.onBeforeRendering(),this._rendered||this.updateAttributes(),this._componentStateFinalizedEventProvider.fireEvent("componentStateFinalized");}finally{this._suppressInvalidation=!1;}this._changedState=[],t._needsShadowDOM()&&n$8(this),this._rendered=!0,e&&this._assignIndividualSlotsToChildren(),this.onAfterRendering();}_assignIndividualSlotsToChildren(){Array.from(this.children).forEach(e=>{e._individualSlot&&e.setAttribute("slot",e._individualSlot);});}_waitForDomRef(){return this._domRefReadyPromise}getDomRef(){if(typeof this._getRealDomRef=="function")return this._getRealDomRef();if(!(!this.shadowRoot||this.shadowRoot.children.length===0))return this.shadowRoot.children[0]}getFocusDomRef(){const t=this.getDomRef();if(t)return t.querySelector("[data-sap-focus-ref]")||t}async getFocusDomRefAsync(){return await this._waitForDomRef(),this.getFocusDomRef()}async focus(t){await this._waitForDomRef();const e=this.getFocusDomRef();e===this?HTMLElement.prototype.focus.call(this,t):e&&typeof e.focus=="function"&&e.focus(t);}fireEvent(t,e,s=!1,n=!0){const o=this._fireEvent(t,e,s,n),i=b$2(t);return i!==t?o&&this._fireEvent(i,e,s,n):o}fireDecoratorEvent(t,e){const s=this.getEventData(t),n=s?s.cancelable:!1,o=s?s.bubbles:!1,i=this._fireEvent(t,e,n,o),r=b$2(t);return r!==t?i&&this._fireEvent(r,e,n,o):i}_fireEvent(t,e,s=!1,n=!0){const o=new CustomEvent(`ui5-${t}`,{detail:e,composed:!1,bubbles:n,cancelable:s}),i=this.dispatchEvent(o);if(a$8(t))return i;const r=new CustomEvent(t,{detail:e,composed:!1,bubbles:n,cancelable:s});return this.dispatchEvent(r)&&i}getEventData(t){return this.constructor.getMetadata().getEvents()[t]}getSlottedNodes(t){return s$9(this[t])}attachComponentStateFinalized(t){this._componentStateFinalizedEventProvider.attachEvent("componentStateFinalized",t);}detachComponentStateFinalized(t){this._componentStateFinalizedEventProvider.detachEvent("componentStateFinalized",t);}get effectiveDir(){return n$i(this.constructor),r$6(this)}get isUI5Element(){return !0}get classes(){return {}}get accessibilityInfo(){return {}}static get observedAttributes(){return this.getMetadata().getAttributesList()}static _needsShadowDOM(){return !!this.template||Object.prototype.hasOwnProperty.call(this.prototype,"render")}static _generateAccessors(){const t=this.prototype,e=this.getMetadata().slotsAreManaged(),s=this.getMetadata().getProperties();for(const[n,o]of Object.entries(s)){r$5(n)||console.warn(`"${n}" is not a valid property name. Use a name that does not collide with DOM APIs`);const i=at(t,n);let r;i?.set&&(r=i.set);let a;i?.get&&(a=i.get),Object.defineProperty(t,n,{get(){return a?a.call(this):this._state[n]},set(h){const m=this.constructor,l=a?a.call(this):this._state[n];l!==h&&(r?r.call(this,h):this._state[n]=h,v$1.call(this,{type:"property",name:n,newValue:h,oldValue:l}),this._rendered&&this._updateAttribute(n,h),m.getMetadata().isFormAssociated()&&e$5(this));}});}if(e){const n=this.getMetadata().getSlots();for(const[o,i]of Object.entries(n)){r$5(o)||console.warn(`"${o}" is not a valid property name. Use a name that does not collide with DOM APIs`);const r=i.propertyName||o,a={get(){return this._state[r]!==void 0?this._state[r]:[]},set(){throw new Error("Cannot set slot content directly, use the DOM APIs (appendChild, removeChild, etc...)")}};Object.defineProperty(t,r,a),r!==c$9(r)&&Object.defineProperty(t,c$9(r),a);}}}static{this.metadata={};}static{this.styles="";}static get dependencies(){return []}static cacheUniqueDependencies(){const t=this.dependencies.filter((e,s,n)=>n.indexOf(e)===s);I$2.set(this,t);}static getUniqueDependencies(){return I$2.has(this)||this.cacheUniqueDependencies(),I$2.get(this)||[]}static async onDefine(){return Promise.resolve()}static fetchI18nBundles(){return Promise.all(Object.entries(this.getMetadata().getI18n()).map(t=>{const{bundleName:e}=t[1];return f$5(e)}))}static fetchCLDR(){return this.getMetadata().needsCLDR()?u$4(s$5().getLanguage(),s$5().getRegion(),s$5().getScript()):Promise.resolve()}static define(){const t=async()=>{await l$e();const i=await Promise.all([this.fetchI18nBundles(),this.fetchCLDR(),this.onDefine()]),[r]=i;Object.entries(this.getMetadata().getI18n()).forEach((a,h)=>{const m=a[0],l=a[1].target;l[m]=r[h];}),this.asyncFinished=!0;};this.definePromise=t();const e=this.getMetadata().getTag();this.getMetadata().getFeatures().forEach(i=>{F$1(i)&&this.cacheUniqueDependencies(),b$7(i,this,this.cacheUniqueDependencies.bind(this));});const n=w$5(e),o=customElements.get(e);return o&&!n?y$7(e):o||(this._generateAccessors(),h$5(e),customElements.define(e,this)),this}static getMetadata(){if(this.hasOwnProperty("_metadata"))return this._metadata;const t=[this.metadata];let e=this;for(;e!==S;)e=Object.getPrototypeOf(e),t.unshift(e.metadata);const s=e$h({},...t);return this._metadata=new p$3(s),this._metadata}get validity(){return this._internals.validity}get validationMessage(){return this._internals.validationMessage}checkValidity(){return this._internals.checkValidity()}reportValidity(){return this._internals.reportValidity()}};const _$1=d=>"isUI5Element"in d; + + (function() { + /* Copyright Google Inc. + * Licensed under the Apache Licence Version 2.0 + * Autogenerated at Tue May 22 10:18:21 PDT 2012 + * \@overrides window + * \@provides cssSchema, CSS_PROP_BIT_QUANTITY, CSS_PROP_BIT_HASH_VALUE, CSS_PROP_BIT_NEGATIVE_QUANTITY, CSS_PROP_BIT_QSTRING_CONTENT, CSS_PROP_BIT_QSTRING_URL, CSS_PROP_BIT_HISTORY_INSENSITIVE, CSS_PROP_BIT_Z_INDEX, CSS_PROP_BIT_ALLOWED_IN_LINK */ + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_QUANTITY = 1; + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_HASH_VALUE = 2; + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_NEGATIVE_QUANTITY = 4; + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_QSTRING_CONTENT = 8; + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_QSTRING_URL = 16; + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_Z_INDEX = 64; + /** + * @const + * @type {number} + */ + var CSS_PROP_BIT_ALLOWED_IN_LINK = 128; + var cssSchema = (function () { + var s = [ + 'rgb(?:\\(\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)|a\\(\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0|\\d+(?:\\.\\d+)?%)\\s*,\\s*(?:\\d+|0(?:\\.\\d+)?|\\.\\d+|1(?:\\.0+)?|0|\\d+(?:\\.\\d+)?%)) *\\)' + ], c = [ /^ *$/i, RegExp('^ *(?:\\s*' + s[ 0 ] + '|(?:\\s*' + s[ 0 ] + + ')?)+ *$', 'i'), RegExp('^ *\\s*' + s[ 0 ] + ' *$', 'i'), + RegExp('^ *\\s*' + s[ 0 ] + '\\s*' + s[ 0 ] + ' *$', 'i') ], L = [ [ + 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', + 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', + 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', + 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', + 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', + 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', + 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', + 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', + 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', + 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', + 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', + 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', + 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', + 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', + 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', + 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', + 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', + 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', + 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', + 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', + 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', + 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', + 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', + 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', + 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', + 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', + 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', + 'yellowgreen' ], [ 'all-scroll', 'col-resize', 'crosshair', 'default', + 'e-resize', 'hand', 'help', 'move', 'n-resize', 'ne-resize', 'no-drop', + 'not-allowed', 'nw-resize', 'pointer', 'progress', 'row-resize', + 's-resize', 'se-resize', 'sw-resize', 'text', 'vertical-text', + 'w-resize', 'wait' ], [ '-moz-inline-box', '-moz-inline-stack', + 'block', 'inline', 'inline-block', 'inline-table', 'list-item', + 'run-in', 'table', 'table-caption', 'table-cell', 'table-column', + 'table-column-group', 'table-footer-group', 'table-header-group', + 'table-row', 'table-row-group' ], [ 'armenian', 'circle', 'decimal', + 'decimal-leading-zero', 'disc', 'georgian', 'lower-alpha', + 'lower-greek', 'lower-latin', 'lower-roman', 'square', 'upper-alpha', + 'upper-latin', 'upper-roman' ], [ '100', '200', '300', '400', '500', + '600', '700', '800', '900', 'bold', 'bolder', 'lighter' ], [ + 'condensed', 'expanded', 'extra-condensed', 'extra-expanded', + 'narrower', 'semi-condensed', 'semi-expanded', 'ultra-condensed', + 'ultra-expanded', 'wider' ], [ 'behind', 'center-left', 'center-right', + 'far-left', 'far-right', 'left-side', 'leftwards', 'right-side', + 'rightwards' ], [ 'large', 'larger', 'small', 'smaller', 'x-large', + 'x-small', 'xx-large', 'xx-small' ], [ '-moz-pre-wrap', '-o-pre-wrap', + '-pre-wrap', 'nowrap', 'pre', 'pre-line', 'pre-wrap' ], [ 'dashed', + 'dotted', 'double', 'groove', 'outset', 'ridge', 'solid' ], [ + 'baseline', 'middle', 'sub', 'super', 'text-bottom', 'text-top' ], [ + 'caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar' + ], [ 'fast', 'faster', 'slow', 'slower', 'x-fast', 'x-slow' ], [ 'above', + 'below', 'higher', 'level', 'lower' ], [ 'border-box', 'contain', + 'content-box', 'cover', 'padding-box' ], [ 'cursive', 'fantasy', + 'monospace', 'sans-serif', 'serif' ], [ 'loud', 'silent', 'soft', + 'x-loud', 'x-soft' ], [ 'no-repeat', 'repeat-x', 'repeat-y', 'round', + 'space' ], [ 'blink', 'line-through', 'overline', 'underline' ], [ + 'high', 'low', 'x-high', 'x-low' ], [ 'absolute', 'relative', 'static' + ], [ 'capitalize', 'lowercase', 'uppercase' ], [ 'child', 'female', + 'male' ], [ 'bidi-override', 'embed' ], [ 'bottom', 'top' ], [ 'clip', + 'ellipsis' ], [ 'continuous', 'digits' ], [ 'hide', 'show' ], [ + 'inside', 'outside' ], [ 'italic', 'oblique' ], [ 'left', 'right' ], [ + 'ltr', 'rtl' ], [ 'no-content', 'no-display' ], [ 'suppress', + 'unrestricted' ], [ 'thick', 'thin' ], [ ',' ], [ '/' ], [ 'always' ], + [ 'auto' ], [ 'avoid' ], [ 'both' ], [ 'break-word' ], [ 'center' ], [ + 'code' ], [ 'collapse' ], [ 'fixed' ], [ 'hidden' ], [ 'inherit' ], [ + 'inset' ], [ 'invert' ], [ 'justify' ], [ 'local' ], [ 'medium' ], [ + 'mix' ], [ 'none' ], [ 'normal' ], [ 'once' ], [ 'repeat' ], [ 'scroll' + ], [ 'separate' ], [ 'small-caps' ], [ 'spell-out' ], [ 'transparent' ], + [ 'visible' ] ]; + return { + '-moz-border-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 36 ] ] + }, + '-moz-border-radius-bottomleft': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-moz-border-radius-bottomright': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-moz-border-radius-topleft': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-moz-border-radius-topright': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-moz-box-shadow': { + 'cssExtra': c[ 1 ], + 'cssAlternates': [ 'boxShadow' ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] + }, + '-moz-opacity': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 47 ] ] + }, + '-moz-outline': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 49 ], L[ 52 ], L[ 54 ] ] + }, + '-moz-outline-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 49 ] ] + }, + '-moz-outline-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + '-moz-outline-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + '-o-text-overflow': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 25 ] ] + }, + '-webkit-border-bottom-left-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-bottom-right-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 36 ] ] + }, + '-webkit-border-radius-bottom-left': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-radius-bottom-right': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-radius-top-left': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-radius-top-right': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-top-left-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-border-top-right-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + '-webkit-box-shadow': { + 'cssExtra': c[ 1 ], + 'cssAlternates': [ 'boxShadow' ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] + }, + 'azimuth': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 6 ], L[ 30 ], L[ 42 ], L[ 47 ] ] + }, + 'background': { + 'cssExtra': RegExp('^ *(?:\\s*' + s[ 0 ] + '){0,2} *$', 'i'), + 'cssPropBits': 23, + 'cssLitGroup': [ L[ 0 ], L[ 14 ], L[ 17 ], L[ 24 ], L[ 30 ], L[ 35 ], + L[ 36 ], L[ 38 ], L[ 42 ], L[ 45 ], L[ 47 ], L[ 51 ], L[ 54 ], L[ 57 + ], L[ 58 ], L[ 62 ] ] + }, + 'background-attachment': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 35 ], L[ 45 ], L[ 51 ], L[ 58 ] ] + }, + 'background-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 130, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] + }, + 'background-image': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 35 ], L[ 54 ] ] + }, + 'background-position': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 24 ], L[ 30 ], L[ 35 ], L[ 42 ] ] + }, + 'background-repeat': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 17 ], L[ 35 ], L[ 57 ] ] + }, + 'border': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 52 ], L[ 54 ], L[ 62 ] ] + }, + 'border-bottom': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 52 ], L[ 54 ], L[ 62 ] ] + }, + 'border-bottom-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] + }, + 'border-bottom-left-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + 'border-bottom-right-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + 'border-bottom-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + 'border-bottom-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + 'border-collapse': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 44 ], L[ 47 ], L[ 59 ] ] + }, + 'border-color': { + 'cssExtra': RegExp('^ *(?:\\s*' + s[ 0 ] + '){1,4} *$', 'i'), + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] + }, + 'border-left': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 52 ], L[ 54 ], L[ 62 ] ] + }, + 'border-left-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] + }, + 'border-left-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + 'border-left-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + 'border-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 36 ] ] + }, + 'border-right': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 52 ], L[ 54 ], L[ 62 ] ] + }, + 'border-right-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] + }, + 'border-right-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + 'border-right-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + 'border-spacing': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'border-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + 'border-top': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 52 ], L[ 54 ], L[ 62 ] ] + }, + 'border-top-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 62 ] ] + }, + 'border-top-left-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + 'border-top-right-radius': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5 + }, + 'border-top-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + 'border-top-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + 'border-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + 'bottom': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'box-shadow': { + 'cssExtra': c[ 1 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] + }, + 'caption-side': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 24 ], L[ 47 ] ] + }, + 'clear': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 30 ], L[ 40 ], L[ 47 ], L[ 54 ] ] + }, + 'clip': { + 'cssExtra': + /^ *\s*rect\(\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto)\s*,\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto)\s*,\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto)\s*,\s*(?:0|[+\-]?\d+(?:\.\d+)?(?:[cem]m|ex|in|p[ctx])|auto) *\) *$/i, + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 130, + 'cssLitGroup': [ L[ 0 ], L[ 47 ] ] + }, + 'content': { 'cssPropBits': 0 }, + 'counter-increment': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'counter-reset': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'cue': { + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'cue-after': { + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'cue-before': { + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'cursor': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 144, + 'cssLitGroup': [ L[ 1 ], L[ 35 ], L[ 38 ], L[ 47 ] ] + }, + 'direction': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 31 ], L[ 47 ] ] + }, + 'display': { + 'cssPropBits': 32, + 'cssLitGroup': [ L[ 2 ], L[ 47 ], L[ 54 ] ] + }, + 'elevation': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 13 ], L[ 47 ] ] + }, + 'empty-cells': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 27 ], L[ 47 ] ] + }, + 'filter': { + 'cssExtra': + /^ *(?:\s*alpha\(\s*opacity\s*=\s*(?:0|\d+(?:\.\d+)?%|[+\-]?\d+(?:\.\d+)?) *\))+ *$/i, + 'cssPropBits': 32 + }, + 'float': { + 'cssAlternates': [ 'cssFloat', 'styleFloat' ], + 'cssPropBits': 32, + 'cssLitGroup': [ L[ 30 ], L[ 47 ], L[ 54 ] ] + }, + 'font': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 9, + 'cssLitGroup': [ L[ 4 ], L[ 7 ], L[ 11 ], L[ 15 ], L[ 29 ], L[ 35 ], L[ + 36 ], L[ 47 ], L[ 52 ], L[ 55 ], L[ 60 ] ] + }, + 'font-family': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 8, + 'cssLitGroup': [ L[ 15 ], L[ 35 ], L[ 47 ] ] + }, + 'font-size': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 7 ], L[ 47 ], L[ 52 ] ] + }, + 'font-stretch': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 5 ], L[ 55 ] ] + }, + 'font-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 29 ], L[ 47 ], L[ 55 ] ] + }, + 'font-variant': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 47 ], L[ 55 ], L[ 60 ] ] + }, + 'font-weight': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 4 ], L[ 47 ], L[ 55 ] ], + // ##### BEGIN: MODIFIED BY SAP + 'cssLitNumeric': true + // ##### END: MODIFIED BY SAP + }, + 'height': { + 'cssPropBits': 37, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'left': { + 'cssPropBits': 37, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'letter-spacing': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ], L[ 55 ] ] + }, + 'line-height': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 47 ], L[ 55 ] ] + }, + 'list-style': { + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 3 ], L[ 28 ], L[ 47 ], L[ 54 ] ] + }, + 'list-style-image': { + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'list-style-position': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 28 ], L[ 47 ] ] + }, + 'list-style-type': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 3 ], L[ 47 ], L[ 54 ] ] + }, + 'margin': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'margin-bottom': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'margin-left': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'margin-right': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'margin-top': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'max-height': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 38 ], L[ 47 ], L[ 54 ] ] + }, + 'max-width': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 38 ], L[ 47 ], L[ 54 ] ] + }, + 'min-height': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'min-width': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'opacity': { + 'cssPropBits': 33, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'outline': { + 'cssExtra': c[ 3 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 9 ], L[ 34 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ + 49 ], L[ 52 ], L[ 54 ] ] + }, + 'outline-color': { + 'cssExtra': c[ 2 ], + 'cssPropBits': 2, + 'cssLitGroup': [ L[ 0 ], L[ 47 ], L[ 49 ] ] + }, + 'outline-style': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 9 ], L[ 46 ], L[ 47 ], L[ 48 ], L[ 54 ] ] + }, + 'outline-width': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 34 ], L[ 47 ], L[ 52 ] ] + }, + 'overflow': { + 'cssPropBits': 32, + 'cssLitGroup': [ L[ 38 ], L[ 46 ], L[ 47 ], L[ 58 ], L[ 63 ] ] + }, + 'overflow-x': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 32 ], L[ 38 ], L[ 46 ], L[ 58 ], L[ 63 ] ] + }, + 'overflow-y': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 32 ], L[ 38 ], L[ 46 ], L[ 58 ], L[ 63 ] ] + }, + 'padding': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'padding-bottom': { + 'cssPropBits': 33, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'padding-left': { + 'cssPropBits': 33, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'padding-right': { + 'cssPropBits': 33, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'padding-top': { + 'cssPropBits': 33, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'page-break-after': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 30 ], L[ 37 ], L[ 38 ], L[ 39 ], L[ 47 ] ] + }, + 'page-break-before': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 30 ], L[ 37 ], L[ 38 ], L[ 39 ], L[ 47 ] ] + }, + 'page-break-inside': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 38 ], L[ 39 ], L[ 47 ] ] + }, + 'pause': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'pause-after': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'pause-before': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'pitch': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 19 ], L[ 47 ], L[ 52 ] ] + }, + 'pitch-range': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'play-during': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 16, + 'cssLitGroup': [ L[ 38 ], L[ 47 ], L[ 53 ], L[ 54 ], L[ 57 ] ] + }, + 'position': { + 'cssPropBits': 32, + 'cssLitGroup': [ L[ 20 ], L[ 47 ] ] + }, + 'quotes': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 47 ], L[ 54 ] ] + }, + 'richness': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'right': { + 'cssPropBits': 37, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'speak': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 47 ], L[ 54 ], L[ 55 ], L[ 61 ] ] + }, + 'speak-header': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 37 ], L[ 47 ], L[ 56 ] ] + }, + 'speak-numeral': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 26 ], L[ 47 ] ] + }, + 'speak-punctuation': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 43 ], L[ 47 ], L[ 54 ] ] + }, + 'speech-rate': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 12 ], L[ 47 ], L[ 52 ] ] + }, + 'stress': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'table-layout': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 38 ], L[ 45 ], L[ 47 ] ] + }, + 'text-align': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 30 ], L[ 42 ], L[ 47 ], L[ 50 ] ] + }, + 'text-decoration': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 18 ], L[ 47 ], L[ 54 ] ] + }, + 'text-indent': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ] ] + }, + 'text-overflow': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 25 ] ] + }, + 'text-shadow': { + 'cssExtra': c[ 1 ], + 'cssPropBits': 7, + 'cssLitGroup': [ L[ 0 ], L[ 35 ], L[ 48 ], L[ 54 ] ] + }, + 'text-transform': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 21 ], L[ 47 ], L[ 54 ] ] + }, + 'text-wrap': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 33 ], L[ 54 ], L[ 55 ] ] + }, + 'top': { + 'cssPropBits': 37, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'unicode-bidi': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 23 ], L[ 47 ], L[ 55 ] ] + }, + 'vertical-align': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 10 ], L[ 24 ], L[ 47 ] ] + }, + 'visibility': { + 'cssPropBits': 32, + 'cssLitGroup': [ L[ 44 ], L[ 46 ], L[ 47 ], L[ 63 ] ] + }, + 'voice-family': { + 'cssExtra': c[ 0 ], + 'cssPropBits': 8, + 'cssLitGroup': [ L[ 22 ], L[ 35 ], L[ 47 ] ] + }, + 'volume': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 16 ], L[ 47 ], L[ 52 ] ] + }, + 'white-space': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 8 ], L[ 47 ], L[ 55 ] ] + }, + 'width': { + 'cssPropBits': 33, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'word-spacing': { + 'cssPropBits': 5, + 'cssLitGroup': [ L[ 47 ], L[ 55 ] ] + }, + 'word-wrap': { + 'cssPropBits': 0, + 'cssLitGroup': [ L[ 41 ], L[ 55 ] ] + }, + 'z-index': { + 'cssPropBits': 69, + 'cssLitGroup': [ L[ 38 ], L[ 47 ] ] + }, + 'zoom': { + 'cssPropBits': 1, + 'cssLitGroup': [ L[ 55 ] ] } - tokens.length = j; - return tokens; }; })(); + if (typeof window !== 'undefined') { + window['cssSchema'] = cssSchema; + } + // Copyright (C) 2011 Google Inc. + // + // 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. + + /** + * A lexical scannar for CSS3 as defined at http://www.w3.org/TR/css3-syntax . + * + * @author Mike Samuel + * \@provides lexCss, decodeCss + * \@overrides window + */ + + var lexCss; + var decodeCss; + + (function () { - // Exports for closure compiler. - if (typeof window !== 'undefined') { - window['lexCss'] = lexCss; - window['decodeCss'] = decodeCss; + /** + * Decodes an escape sequence as specified in CSS3 section 4.1. + * http://www.w3.org/TR/css3-syntax/#characters + * @private + */ + function decodeCssEscape(s) { + var i = parseInt(s.substring(1), 16); + // If parseInt didn't find a hex diigt, it returns NaN so return the + // escaped character. + // Otherwise, parseInt will stop at the first non-hex digit so there's no + // need to worry about trailing whitespace. + if (i > 0xffff) { + // A supplemental codepoint. + return i -= 0x10000, + String.fromCharCode( + 0xd800 + (i >> 10), + 0xdc00 + (i & 0x3FF)); + } else if (i == i) { + return String.fromCharCode(i); + } else if (s[1] < ' ') { + // "a backslash followed by a newline is ignored". + return ''; + } else { + return s[1]; + } } - // Copyright (C) 2011 Google Inc. - // - // 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. /** - * @fileoverview - * JavaScript support for client-side CSS sanitization. - * The CSS property schema API is defined in CssPropertyPatterns.java which - * is used to generate css-defs.js. - * - * @author mikesamuel@gmail.com - * \@requires CSS_PROP_BIT_ALLOWED_IN_LINK - * \@requires CSS_PROP_BIT_HASH_VALUE - * \@requires CSS_PROP_BIT_NEGATIVE_QUANTITY - * \@requires CSS_PROP_BIT_QSTRING_CONTENT - * \@requires CSS_PROP_BIT_QSTRING_URL - * \@requires CSS_PROP_BIT_QUANTITY - * \@requires CSS_PROP_BIT_Z_INDEX - * \@requires cssSchema - * \@requires decodeCss - * \@requires html4 - * \@overrides window - * \@requires parseCssStylesheet - * \@provides sanitizeCssProperty - * \@provides sanitizeCssSelectors - * \@provides sanitizeStylesheet + * Returns an equivalent CSS string literal given plain text: foo -> "foo". + * @private */ + function escapeCssString(s, replacer) { + return '"' + s.replace(/[\u0000-\u001f\\\"<>]/g, replacer) + '"'; + } /** - * Given a series of normalized CSS tokens, applies a property schema, as - * defined in CssPropertyPatterns.java, and sanitizes the tokens in place. - * @param property a property name. - * @param propertySchema a property of cssSchema as defined by - * CssPropertyPatterns.java - * @param tokens as parsed by lexCss. Modified in place. - * @param opt_naiveUriRewriter a URI rewriter; an object with a "rewrite" - * function that takes a URL and returns a safe URL. + * Maps chars to CSS escaped equivalents: "\n" -> "\\a ". + * @private */ - var sanitizeCssProperty = (function () { - var NOEFFECT_URL = 'url("about:blank")'; - /** - * The set of characters that need to be normalized inside url("..."). - * We normalize newlines because they are not allowed inside quoted strings, - * normalize quote characters, angle-brackets, and asterisks because they - * could be used to break out of the URL or introduce targets for CSS - * error recovery. We normalize parentheses since they delimit unquoted - * URLs and calls and could be a target for error recovery. - */ - var NORM_URL_REGEXP = /[\n\f\r\"\'()*<>]/g; - /** The replacements for NORM_URL_REGEXP. */ - var NORM_URL_REPLACEMENTS = { - '\n': '%0a', - '\f': '%0c', - '\r': '%0d', - '"': '%22', - '\'': '%27', - '(': '%28', - ')': '%29', - '*': '%2a', - '<': '%3c', - '>': '%3e' - }; + function escapeCssStrChar(ch) { + return cssStrChars[ch] + || (cssStrChars[ch] = '\\' + ch.charCodeAt(0).toString(16) + ' '); + } + /** + * Maps chars to URI escaped equivalents: "\n" -> "%0a". + * @private + */ + function escapeCssUrlChar(ch) { + return cssUrlChars[ch] + || (cssUrlChars[ch] = (ch < '\x10' ? '%0' : '%') + + ch.charCodeAt(0).toString(16)); + } - function normalizeUrl(s) { - if ('string' === typeof s) { - return 'url("' + s.replace(NORM_URL_REGEXP, normalizeUrlChar) + '")'; - } else { - return NOEFFECT_URL; - } - } - function normalizeUrlChar(ch) { - return NORM_URL_REPLACEMENTS[ch]; - } + /** + * Mapping of CSS special characters to escaped equivalents. + * @private + */ + var cssStrChars = { + '\\': '\\\\' + }; + + /** + * Mapping of CSS special characters to URL-escaped equivalents. + * @private + */ + var cssUrlChars = { + '\\': '%5c' + }; + + // The comments below are copied from the CSS3 module syntax at + // http://www.w3.org/TR/css3-syntax . + // These string constants minify out when this is run-through closure + // compiler. + // Rules that have been adapted have comments prefixed with "Diff:", and + // where rules have been combined to avoid back-tracking in the regex engine + // or to work around limitations, there is a comment prefixed with + // "NewRule:". + + // In the below, we assume CRLF and CR have been normalize to CR. + + // wc ::= #x9 | #xA | #xC | #xD | #x20 + var WC = '[\\t\\n\\f ]'; + // w ::= wc* + var W = WC + '*'; + // nl ::= #xA | #xD #xA | #xD | #xC + var NL = '[\\n\\f]'; + // nonascii ::= [#x80-#xD7FF#xE000-#xFFFD#x10000-#x10FFFF] + // NewRule: Supplemental codepoints are represented as surrogate pairs in JS. + var SURROGATE_PAIR = '[\\ud800-\\udbff][\\udc00-\\udfff]'; + var NONASCII = '[\\u0080-\\ud7ff\\ue000-\\ufffd]|' + SURROGATE_PAIR; + // unicode ::= '\' [0-9a-fA-F]{1,6} wc? + // NewRule: No point in having ESCAPE do (\\x|\\y) + var UNICODE_TAIL = '[0-9a-fA-F]{1,6}' + WC + '?'; + // escape ::= unicode + // | '\' [#x20-#x7E#x80-#xD7FF#xE000-#xFFFD#x10000-#x10FFFF] + // NewRule: Below we use escape tail to efficiently match an escape or a + // line continuation so we can decode string content. + var ESCAPE_TAIL = '(?:' + UNICODE_TAIL + + '|[\\u0020-\\u007e\\u0080-\\ud7ff\\ue000\\ufffd]|' + + SURROGATE_PAIR + ')'; + var ESCAPE = '\\\\' + ESCAPE_TAIL; + // urlchar ::= [#x9#x21#x23-#x26#x28-#x7E] | nonascii | escape + var URLCHAR = '(?:[\\t\\x21\\x23-\\x26\\x28-\\x5b\\x5d-\\x7e]|' + + NONASCII + '|' + ESCAPE + ')'; + // stringchar ::= urlchar | #x20 | '\' nl + // We ignore mismatched surrogate pairs inside strings, so stringchar + // simplifies to a non-(quote|newline|backslash) or backslash any. + // Since we normalize CRLF to a single code-unit, there is no special + // handling needed for '\\' + CRLF. + var STRINGCHAR = '[^\'"\\n\\f\\\\]|\\\\[\\s\\S]'; + // string ::= '"' (stringchar | "'")* '"' | "'" (stringchar | '"')* "'" + var STRING = '"(?:\'|' + STRINGCHAR + ')*"' + + '|\'(?:\"|' + STRINGCHAR + ')*\''; + // num ::= [0-9]+ | [0-9]* '.' [0-9]+ + // Diff: We attach signs to num tokens. + var NUM = '[-+]?(?:[0-9]+(?:[.][0-9]+)?|[.][0-9]+)'; + // nmstart ::= [a-zA-Z] | '_' | nonascii | escape + var NMSTART = '(?:[a-zA-Z_]|' + NONASCII + '|' + ESCAPE + ')'; + // nmchar ::= [a-zA-Z0-9] | '-' | '_' | nonascii | escape + var NMCHAR = '(?:[a-zA-Z0-9_-]|' + NONASCII + '|' + ESCAPE + ')'; + // ident ::= '-'? nmstart nmchar* + var IDENT = '-?' + NMSTART + NMCHAR + '*'; + + // NewRule: union of IDENT, ATKEYWORD, HASH, but excluding #[0-9]. + var WORD_TERM = '(?:@?-?' + NMSTART + '|#)' + NMCHAR + '*'; + var NUMERIC_VALUE = NUM + '(?:%|' + IDENT + ')?'; + // URI ::= "url(" w (string | urlchar* ) w ")" + var URI = 'url[(]' + W + '(?:' + STRING + '|' + URLCHAR + '*)' + W + '[)]'; + // UNICODE-RANGE ::= "U+" [0-9A-F?]{1,6} ('-' [0-9A-F]{1,6})? + var UNICODE_RANGE = 'U[+][0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?'; + // CDO ::= "<\!--" + var CDO = '<\!--'; + // CDC ::= "-->" + var CDC = '-->'; + // S ::= wc+ + var S = WC + '+'; + // COMMENT ::= "/*" [^*]* '*'+ ([^/] [^*]* '*'+)* "/" + // Diff: recognizes // comments. + var COMMENT = '/(?:[*][^*]*[*]+(?:[^/][^*]*[*]+)*/|/[^\\n\\f]*)'; + // FUNCTION ::= ident '(' + // Diff: We exclude url explicitly. + // TODO: should we be tolerant of "fn ("? + // ##### BEGIN: MODIFIED BY SAP + // Avoid risk of 'catastrophic backtracking' when unicode escapes are used + // var FUNCTION = '(?!url[(])' + IDENT + '[(]'; + var FUNCTION = '(?!url[(])(?=(' + IDENT + '))\\1[(]'; + // NewRule: one rule for all the comparison operators. + var CMP_OPS = '[~|^$*]='; + // CHAR ::= any character not matched by the above rules, except for " or ' + // Diff: We exclude / and \ since they are handled above to prevent + // /* without a following */ from combining when comments are concatenated. + var CHAR = '[^"\'\\\\/]|/(?![/*])'; + // BOM ::= #xFEFF + var BOM = '\\uFEFF'; + + var CSS_TOKEN = new RegExp([ + BOM, UNICODE_RANGE, URI, FUNCTION, WORD_TERM, STRING, NUMERIC_VALUE, + CDO, CDC, S, COMMENT, CMP_OPS, CHAR].join("|"), 'gi'); - // From RFC3986 - var URI_SCHEME_RE = new RegExp( - '^' + - '(?:' + - '([^:\/?# ]+)' + // scheme - ':)?' - ); - - var ALLOWED_URI_SCHEMES = /^(?:https?|mailto)$/i; - - function safeUri(uri, prop, naiveUriRewriter) { - if (!naiveUriRewriter) { return null; } - var parsed = ('' + uri).match(URI_SCHEME_RE); - if (parsed && (!parsed[1] || ALLOWED_URI_SCHEMES.test(parsed[1]))) { - return naiveUriRewriter(uri, prop); - } else { - return null; - } - } + /** + * Decodes CSS escape sequences in a CSS string body. + */ + decodeCss = function (css) { + return css.replace( + new RegExp('\\\\(?:' + ESCAPE_TAIL + '|' + NL + ')', 'g'), + decodeCssEscape); + }; - function unionArrays(arrs) { - var map = {}; - for (var i = arrs.length; --i >= 0;) { - var arr = arrs[i]; - for (var j = arr.length; --j >= 0;) { - map[arr[j]] = ALLOWED_LITERAL; - } - } - return map; + /** + * Given CSS Text, returns an array of normalized tokens. + * @param {string} cssText + * @return {Array.} tokens where all ignorable token sequences have + * been reduced to a single {@code " "} and all strings and + * {@code url(...)} tokens have been normalized to use double quotes as + * delimiters and to not otherwise contain double quotes. + */ + lexCss = function (cssText) { + cssText = '' + cssText; + var tokens = cssText.replace(/\r\n?/g, '\n') // Normalize CRLF & CR to LF. + .match(CSS_TOKEN) || []; + var j = 0; + var last = ' '; + for (var i = 0, n = tokens.length; i < n; ++i) { + // Normalize all escape sequences. We will have to re-escape some + // codepoints in string and url(...) bodies but we already know the + // boundaries. + // We might mistakenly treat a malformed identifier like \22\20\22 as a + // string, but that will not break any valid stylesheets since we requote + // and re-escape in string below. + var tok = decodeCss(tokens[i]); + var len = tok.length; + var cc = tok.charCodeAt(0); + tok = + // All strings should be double quoted, and the body should never + // contain a double quote. + (cc == '"'.charCodeAt(0) || cc == '\''.charCodeAt(0)) + ? escapeCssString(tok.substring(1, len - 1), escapeCssStrChar) + // A breaking ignorable token should is replaced with a single space. + : (cc == '/'.charCodeAt(0) && len > 1 // Comment. + || tok == '\\' || tok == CDC || tok == CDO || tok == '\ufeff' + // Characters in W. + || cc <= ' '.charCodeAt(0)) + ? ' ' + // Make sure that all url(...)s are double quoted. + : /url\(/i.test(tok) + ? 'url(' + escapeCssString( + tok.replace( + new RegExp('^url\\(' + W + '["\']?|["\']?' + W + '\\)$', 'gi'), + ''), + escapeCssUrlChar) + + ')' + // Escapes in identifier like tokens will have been normalized above. + : tok; + // Merge adjacent space tokens. + if (last != tok || tok != ' ') { + tokens[j++] = last = tok; + } + } + tokens.length = j; + return tokens; + }; + })(); + + // Exports for closure compiler. + if (typeof window !== 'undefined') { + window['lexCss'] = lexCss; + window['decodeCss'] = decodeCss; + } + // Copyright (C) 2011 Google Inc. + // + // 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. + + /** + * @fileoverview + * JavaScript support for client-side CSS sanitization. + * The CSS property schema API is defined in CssPropertyPatterns.java which + * is used to generate css-defs.js. + * + * @author mikesamuel@gmail.com + * \@requires CSS_PROP_BIT_ALLOWED_IN_LINK + * \@requires CSS_PROP_BIT_HASH_VALUE + * \@requires CSS_PROP_BIT_NEGATIVE_QUANTITY + * \@requires CSS_PROP_BIT_QSTRING_CONTENT + * \@requires CSS_PROP_BIT_QSTRING_URL + * \@requires CSS_PROP_BIT_QUANTITY + * \@requires CSS_PROP_BIT_Z_INDEX + * \@requires cssSchema + * \@requires decodeCss + * \@requires html4 + * \@overrides window + * \@requires parseCssStylesheet + * \@provides sanitizeCssProperty + * \@provides sanitizeCssSelectors + * \@provides sanitizeStylesheet + */ + + /** + * Given a series of normalized CSS tokens, applies a property schema, as + * defined in CssPropertyPatterns.java, and sanitizes the tokens in place. + * @param property a property name. + * @param propertySchema a property of cssSchema as defined by + * CssPropertyPatterns.java + * @param tokens as parsed by lexCss. Modified in place. + * @param opt_naiveUriRewriter a URI rewriter; an object with a "rewrite" + * function that takes a URL and returns a safe URL. + */ + var sanitizeCssProperty = (function () { + var NOEFFECT_URL = 'url("about:blank")'; + /** + * The set of characters that need to be normalized inside url("..."). + * We normalize newlines because they are not allowed inside quoted strings, + * normalize quote characters, angle-brackets, and asterisks because they + * could be used to break out of the URL or introduce targets for CSS + * error recovery. We normalize parentheses since they delimit unquoted + * URLs and calls and could be a target for error recovery. + */ + var NORM_URL_REGEXP = /[\n\f\r\"\'()*<>]/g; + /** The replacements for NORM_URL_REGEXP. */ + var NORM_URL_REPLACEMENTS = { + '\n': '%0a', + '\f': '%0c', + '\r': '%0d', + '"': '%22', + '\'': '%27', + '(': '%28', + ')': '%29', + '*': '%2a', + '<': '%3c', + '>': '%3e' + }; + + + function normalizeUrl(s) { + if ('string' === typeof s) { + return 'url("' + s.replace(NORM_URL_REGEXP, normalizeUrlChar) + '")'; + } else { + return NOEFFECT_URL; } + } + function normalizeUrlChar(ch) { + return NORM_URL_REPLACEMENTS[ch]; + } - /** - * Normalize tokens within a function call they can match against - * cssSchema[propName].cssExtra. - * @return the exclusive end in tokens of the function call. - */ - function normalizeFunctionCall(tokens, start) { - var parenDepth = 1, end = start + 1, n = tokens.length; - while (end < n && parenDepth) { - // TODO: Can URLs appear in functions? - var token = tokens[end++]; - parenDepth += (token === '(' ? 1 : token === ')' ? -1 : 0); - } - return end; + // From RFC3986 + var URI_SCHEME_RE = new RegExp( + '^' + + '(?:' + + '([^:\/?# ]+)' + // scheme + ':)?' + ); + + var ALLOWED_URI_SCHEMES = /^(?:https?|mailto)$/i; + + function safeUri(uri, prop, naiveUriRewriter) { + if (!naiveUriRewriter) { return null; } + var parsed = ('' + uri).match(URI_SCHEME_RE); + if (parsed && (!parsed[1] || ALLOWED_URI_SCHEMES.test(parsed[1]))) { + return naiveUriRewriter(uri, prop); + } else { + return null; } + } - // Used as map value to avoid hasOwnProperty checks. - var ALLOWED_LITERAL = {}; - - return function (property, propertySchema, tokens, opt_naiveUriRewriter) { - var propBits = propertySchema.cssPropBits; - // Used to determine whether to treat quoted strings as URLs or - // plain text content, and whether unrecognized keywords can be quoted - // to treate ['Arial', 'Black'] equivalently to ['"Arial Black"']. - var qstringBits = propBits & ( - CSS_PROP_BIT_QSTRING_CONTENT | CSS_PROP_BIT_QSTRING_URL); - // TODO(mikesamuel): Figure out what to do with props like - // content that admit both URLs and strings. - - // Used to join unquoted keywords into a single quoted string. - var lastQuoted = NaN; - var i = 0, k = 0; - for (;i < tokens.length; ++i) { - // Has the effect of normalizing hex digits, keywords, - // and function names. - var token = tokens[i].toLowerCase(); - var cc = token.charCodeAt(0), cc1, cc2, isnum1, isnum2, end; - var litGroup, litMap; - token = ( - // Strip out spaces. Normally cssparser.js dumps these, but we - // strip them out in case the content doesn't come via cssparser.js. - (cc === ' '.charCodeAt(0)) - ? '' - : (cc === '"'.charCodeAt(0)) - ? ( // Quoted string. - (qstringBits === CSS_PROP_BIT_QSTRING_URL && opt_naiveUriRewriter) - // Sanitize and convert to url("...") syntax. - // Treat url content as case-sensitive. - ? (normalizeUrl( - safeUri( - decodeCss(tokens[i].substring(1, token.length - 1)), - property, - opt_naiveUriRewriter - ) - )) - // Drop if plain text content strings not allowed. - : (qstringBits === CSS_PROP_BIT_QSTRING_CONTENT) ? token : '') - // Preserve hash color literals if allowed. - : (cc === '#'.charCodeAt(0) && /^#(?:[0-9a-f]{3}){1,2}$/.test(token)) - ? (propBits & CSS_PROP_BIT_HASH_VALUE ? token : '') - // ##### BEGIN: MODIFIED BY SAP - // : ('0'.charCodeAt(0) <= cc && cc <= '9'.charCodeAt(0)) - : ('0'.charCodeAt(0) <= cc && cc <= '9'.charCodeAt(0) && !propertySchema.cssLitNumeric) - // ##### END: MODIFIED BY SAP - // A number starting with a digit. - ? ((propBits & CSS_PROP_BIT_QUANTITY) - ? ((propBits & CSS_PROP_BIT_Z_INDEX) - ? (token.match(/^\d{1,7}$/) ? token : '') - : token) - : '') - // Normalize quantities so they don't start with a '.' or '+' sign and - // make sure they all have an integer component so can't be confused - // with a dotted identifier. - // This can't be done in the lexer since ".4" is a valid rule part. - : (cc1 = token.charCodeAt(1), - cc2 = token.charCodeAt(2), - isnum1 = '0'.charCodeAt(0) <= cc1 && cc1 <= '9'.charCodeAt(0), - isnum2 = '0'.charCodeAt(0) <= cc2 && cc2 <= '9'.charCodeAt(0), - // +.5 -> 0.5 if allowed. - (cc === '+'.charCodeAt(0) - && (isnum1 || (cc1 === '.'.charCodeAt(0) && isnum2)))) - ? ((propBits & CSS_PROP_BIT_QUANTITY) - ? ((propBits & CSS_PROP_BIT_Z_INDEX) - ? (token.match(/^\+\d{1,7}$/) ? token : '') - : ((isnum1 ? '' : '0') + token.substring(1))) - : '') - // -.5 -> -0.5 if allowed otherwise -> 0 if quantities allowed. - : (cc === '-'.charCodeAt(0) - && (isnum1 || (cc1 === '.'.charCodeAt(0) && isnum2))) - ? ((propBits & CSS_PROP_BIT_NEGATIVE_QUANTITY) - ? ((propBits & CSS_PROP_BIT_Z_INDEX) - ? (token.match(/^\-\d{1,7}$/) ? token : '') - : ((isnum1 ? '-' : '-0') + token.substring(1))) - : ((propBits & CSS_PROP_BIT_QUANTITY) ? '0' : '')) - // .5 -> 0.5 if allowed. - : (cc === '.'.charCodeAt(0) && isnum1) - ? ((propBits & CSS_PROP_BIT_QUANTITY) ? '0' + token : '') - // Handle url("...") by rewriting the body. - : ('url(' === token.substring(0, 4)) - ? ((opt_naiveUriRewriter && (qstringBits & CSS_PROP_BIT_QSTRING_URL)) - ? normalizeUrl( - safeUri( - tokens[i].substring(5, token.length - 2), - property, - opt_naiveUriRewriter - ) - ) - : '') - // Handle func(...) and literal tokens - // such as keywords and punctuation. - : ( - // Step 1. Combine func(...) into something that can be compared - // against propertySchema.cssExtra. - (token.charAt(token.length-1) === '(') - && (end = normalizeFunctionCall(tokens, i), - // When tokens is - // ['x', ' ', 'rgb(', '255', ',', '0', ',', '0', ')', ' ', 'y'] - // and i is the index of 'rgb(' and end is the index of ')' - // splices tokens to where i now is the index of the whole call: - // ['x', ' ', 'rgb( 255 , 0 , 0 )', ' ', 'y'] - tokens.splice(i, end - i, - token = tokens.slice(i, end).join(' '))), - litGroup = propertySchema.cssLitGroup, - litMap = ( - litGroup - ? (propertySchema.cssLitMap - // Lazily compute the union from litGroup. - || (propertySchema.cssLitMap = unionArrays(litGroup))) - : ALLOWED_LITERAL), // A convenient empty object. - (litMap[token] === ALLOWED_LITERAL - || propertySchema.cssExtra && propertySchema.cssExtra.test(token))) - // Token is in the literal map or matches extra. - ? token - : (/^\w+$/.test(token) - && (qstringBits === CSS_PROP_BIT_QSTRING_CONTENT)) - // Quote unrecognized keywords so font names like - // Arial Bold - // -> - // "Arial Bold" - ? (lastQuoted+1 === k - // If the last token was also a keyword that was quoted, then - // combine this token into that. - ? (tokens[lastQuoted] = tokens[lastQuoted] - .substring(0, tokens[lastQuoted].length-1) + ' ' + token + '"', - token = '') - : (lastQuoted = k, '"' + token + '"')) - // Disallowed. - : ''); - if (token) { - tokens[k++] = token; - } + function unionArrays(arrs) { + var map = {}; + for (var i = arrs.length; --i >= 0;) { + var arr = arrs[i]; + for (var j = arr.length; --j >= 0;) { + map[arr[j]] = ALLOWED_LITERAL; } - // For single URL properties, if the URL failed to pass the sanitizer, - // then just drop it. - if (k === 1 && tokens[0] === NOEFFECT_URL) { k = 0; } - tokens.length = k; - }; - })(); + } + return map; + } /** - * Given a series of tokens, returns two lists of sanitized selectors. - * @param {Array.} selectors In the form produces by csslexer.js. - * @param {string} suffix a suffix that is added to all IDs and which is - * used as a CLASS names so that the returned selectors will only match - * nodes under one with suffix as a class name. - * If suffix is {@code "sfx"}, the selector - * {@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to - * {@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}. - * @return {Array.>} an array of length 2 where the zeroeth - * element contains history-insensitive selectors and the first element - * contains history-sensitive selectors. + * Normalize tokens within a function call they can match against + * cssSchema[propName].cssExtra. + * @return the exclusive end in tokens of the function call. */ - function sanitizeCssSelectors(selectors, suffix) { - // Produce two distinct lists of selectors to sequester selectors that are - // history sensitive (:visited), so that we can disallow properties in the - // property groups for the history sensitive ones. - var historySensitiveSelectors = []; - var historyInsensitiveSelectors = []; - - // Remove any spaces that are not operators. - var k = 0, i; - for (i = 0; i < selectors.length; ++i) { - if (!(selectors[i] == ' ' - && (selectors[i-1] == '>' || selectors[i+1] == '>'))) { - selectors[k++] = selectors[i]; - } + function normalizeFunctionCall(tokens, start) { + var parenDepth = 1, end = start + 1, n = tokens.length; + while (end < n && parenDepth) { + // TODO: Can URLs appear in functions? + var token = tokens[end++]; + parenDepth += (token === '(' ? 1 : token === ')' ? -1 : 0); + } + return end; + } + + // Used as map value to avoid hasOwnProperty checks. + var ALLOWED_LITERAL = {}; + + return function (property, propertySchema, tokens, opt_naiveUriRewriter) { + var propBits = propertySchema.cssPropBits; + // Used to determine whether to treat quoted strings as URLs or + // plain text content, and whether unrecognized keywords can be quoted + // to treate ['Arial', 'Black'] equivalently to ['"Arial Black"']. + var qstringBits = propBits & ( + CSS_PROP_BIT_QSTRING_CONTENT | CSS_PROP_BIT_QSTRING_URL); + // TODO(mikesamuel): Figure out what to do with props like + // content that admit both URLs and strings. + + // Used to join unquoted keywords into a single quoted string. + var lastQuoted = NaN; + var i = 0, k = 0; + for (;i < tokens.length; ++i) { + // Has the effect of normalizing hex digits, keywords, + // and function names. + var token = tokens[i].toLowerCase(); + var cc = token.charCodeAt(0), cc1, cc2, isnum1, isnum2, end; + var litGroup, litMap; + token = ( + // Strip out spaces. Normally cssparser.js dumps these, but we + // strip them out in case the content doesn't come via cssparser.js. + (cc === ' '.charCodeAt(0)) + ? '' + : (cc === '"'.charCodeAt(0)) + ? ( // Quoted string. + (qstringBits === CSS_PROP_BIT_QSTRING_URL && opt_naiveUriRewriter) + // Sanitize and convert to url("...") syntax. + // Treat url content as case-sensitive. + ? (normalizeUrl( + safeUri( + decodeCss(tokens[i].substring(1, token.length - 1)), + property, + opt_naiveUriRewriter + ) + )) + // Drop if plain text content strings not allowed. + : (qstringBits === CSS_PROP_BIT_QSTRING_CONTENT) ? token : '') + // Preserve hash color literals if allowed. + : (cc === '#'.charCodeAt(0) && /^#(?:[0-9a-f]{3}){1,2}$/.test(token)) + ? (propBits & CSS_PROP_BIT_HASH_VALUE ? token : '') + // ##### BEGIN: MODIFIED BY SAP + // : ('0'.charCodeAt(0) <= cc && cc <= '9'.charCodeAt(0)) + : ('0'.charCodeAt(0) <= cc && cc <= '9'.charCodeAt(0) && !propertySchema.cssLitNumeric) + // ##### END: MODIFIED BY SAP + // A number starting with a digit. + ? ((propBits & CSS_PROP_BIT_QUANTITY) + ? ((propBits & CSS_PROP_BIT_Z_INDEX) + ? (token.match(/^\d{1,7}$/) ? token : '') + : token) + : '') + // Normalize quantities so they don't start with a '.' or '+' sign and + // make sure they all have an integer component so can't be confused + // with a dotted identifier. + // This can't be done in the lexer since ".4" is a valid rule part. + : (cc1 = token.charCodeAt(1), + cc2 = token.charCodeAt(2), + isnum1 = '0'.charCodeAt(0) <= cc1 && cc1 <= '9'.charCodeAt(0), + isnum2 = '0'.charCodeAt(0) <= cc2 && cc2 <= '9'.charCodeAt(0), + // +.5 -> 0.5 if allowed. + (cc === '+'.charCodeAt(0) + && (isnum1 || (cc1 === '.'.charCodeAt(0) && isnum2)))) + ? ((propBits & CSS_PROP_BIT_QUANTITY) + ? ((propBits & CSS_PROP_BIT_Z_INDEX) + ? (token.match(/^\+\d{1,7}$/) ? token : '') + : ((isnum1 ? '' : '0') + token.substring(1))) + : '') + // -.5 -> -0.5 if allowed otherwise -> 0 if quantities allowed. + : (cc === '-'.charCodeAt(0) + && (isnum1 || (cc1 === '.'.charCodeAt(0) && isnum2))) + ? ((propBits & CSS_PROP_BIT_NEGATIVE_QUANTITY) + ? ((propBits & CSS_PROP_BIT_Z_INDEX) + ? (token.match(/^\-\d{1,7}$/) ? token : '') + : ((isnum1 ? '-' : '-0') + token.substring(1))) + : ((propBits & CSS_PROP_BIT_QUANTITY) ? '0' : '')) + // .5 -> 0.5 if allowed. + : (cc === '.'.charCodeAt(0) && isnum1) + ? ((propBits & CSS_PROP_BIT_QUANTITY) ? '0' + token : '') + // Handle url("...") by rewriting the body. + : ('url(' === token.substring(0, 4)) + ? ((opt_naiveUriRewriter && (qstringBits & CSS_PROP_BIT_QSTRING_URL)) + ? normalizeUrl( + safeUri( + tokens[i].substring(5, token.length - 2), + property, + opt_naiveUriRewriter + ) + ) + : '') + // Handle func(...) and literal tokens + // such as keywords and punctuation. + : ( + // Step 1. Combine func(...) into something that can be compared + // against propertySchema.cssExtra. + (token.charAt(token.length-1) === '(') + && (end = normalizeFunctionCall(tokens, i), + // When tokens is + // ['x', ' ', 'rgb(', '255', ',', '0', ',', '0', ')', ' ', 'y'] + // and i is the index of 'rgb(' and end is the index of ')' + // splices tokens to where i now is the index of the whole call: + // ['x', ' ', 'rgb( 255 , 0 , 0 )', ' ', 'y'] + tokens.splice(i, end - i, + token = tokens.slice(i, end).join(' '))), + litGroup = propertySchema.cssLitGroup, + litMap = ( + litGroup + ? (propertySchema.cssLitMap + // Lazily compute the union from litGroup. + || (propertySchema.cssLitMap = unionArrays(litGroup))) + : ALLOWED_LITERAL), // A convenient empty object. + (litMap[token] === ALLOWED_LITERAL + || propertySchema.cssExtra && propertySchema.cssExtra.test(token))) + // Token is in the literal map or matches extra. + ? token + : (/^\w+$/.test(token) + && (qstringBits === CSS_PROP_BIT_QSTRING_CONTENT)) + // Quote unrecognized keywords so font names like + // Arial Bold + // -> + // "Arial Bold" + ? (lastQuoted+1 === k + // If the last token was also a keyword that was quoted, then + // combine this token into that. + ? (tokens[lastQuoted] = tokens[lastQuoted] + .substring(0, tokens[lastQuoted].length-1) + ' ' + token + '"', + token = '') + : (lastQuoted = k, '"' + token + '"')) + // Disallowed. + : ''); + if (token) { + tokens[k++] = token; + } + } + // For single URL properties, if the URL failed to pass the sanitizer, + // then just drop it. + if (k === 1 && tokens[0] === NOEFFECT_URL) { k = 0; } + tokens.length = k; + }; + })(); + + /** + * Given a series of tokens, returns two lists of sanitized selectors. + * @param {Array.} selectors In the form produces by csslexer.js. + * @param {string} suffix a suffix that is added to all IDs and which is + * used as a CLASS names so that the returned selectors will only match + * nodes under one with suffix as a class name. + * If suffix is {@code "sfx"}, the selector + * {@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to + * {@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}. + * @return {Array.>} an array of length 2 where the zeroeth + * element contains history-insensitive selectors and the first element + * contains history-sensitive selectors. + */ + function sanitizeCssSelectors(selectors, suffix) { + // Produce two distinct lists of selectors to sequester selectors that are + // history sensitive (:visited), so that we can disallow properties in the + // property groups for the history sensitive ones. + var historySensitiveSelectors = []; + var historyInsensitiveSelectors = []; + + // Remove any spaces that are not operators. + var k = 0, i; + for (i = 0; i < selectors.length; ++i) { + if (!(selectors[i] == ' ' + && (selectors[i-1] == '>' || selectors[i+1] == '>'))) { + selectors[k++] = selectors[i]; } - selectors.length = k; - - // Split around commas. If there is an error in one of the comma separated - // bits, we throw the whole away, but the failure of one selector does not - // affect others. - var n = selectors.length, start = 0; - for (i = 0; i < n; ++i) { - if (selectors[i] == ',') { - processSelector(start, i); - start = i+1; - } + } + selectors.length = k; + + // Split around commas. If there is an error in one of the comma separated + // bits, we throw the whole away, but the failure of one selector does not + // affect others. + var n = selectors.length, start = 0; + for (i = 0; i < n; ++i) { + if (selectors[i] == ',') { + processSelector(start, i); + start = i+1; } - processSelector(start, n); - - - function processSelector(start, end) { - var historySensitive = false; - - // Space around commas is not an operator. - if (selectors[start] === ' ') { ++start; } - if (end-1 !== start && selectors[end] === ' ') { --end; } - - // Split the selector into element selectors, content around - // space (ancestor operator) and '>' (descendant operator). - var out = []; - var lastOperator = start; - var elSelector = ''; - for (var i = start; i < end; ++i) { - var tok = selectors[i]; - var isChild = (tok === '>'); - if (isChild || tok === ' ') { - // We've found the end of a single link in the selector chain. - // We disallow absolute positions relative to html. - elSelector = processElementSelector(lastOperator, i, false); - if (!elSelector || (isChild && /^html/i.test(elSelector))) { - return; - } - lastOperator = i+1; - out.push(elSelector, isChild ? ' > ' : ' '); - } - } - elSelector = processElementSelector(lastOperator, end, true); - if (!elSelector) { return; } - out.push(elSelector); - - function processElementSelector(start, end, last) { - - // Split the element selector into three parts. - // DIV.foo#bar:hover - // ^ ^ - // el classes pseudo - var element, classId, pseudoSelector, tok, elType; - element = ''; - if (start < end) { - tok = selectors[start].toLowerCase(); - if (tok === '*' - || (tok === 'body' && start+1 !== end && !last) - || ('number' === typeof (elType = html4.ELEMENTS[tok]) - && !(elType & html4.eflags.UNSAFE))) { - ++start; - element = tok; - } + } + processSelector(start, n); + + + function processSelector(start, end) { + var historySensitive = false; + + // Space around commas is not an operator. + if (selectors[start] === ' ') { ++start; } + if (end-1 !== start && selectors[end] === ' ') { --end; } + + // Split the selector into element selectors, content around + // space (ancestor operator) and '>' (descendant operator). + var out = []; + var lastOperator = start; + var elSelector = ''; + for (var i = start; i < end; ++i) { + var tok = selectors[i]; + var isChild = (tok === '>'); + if (isChild || tok === ' ') { + // We've found the end of a single link in the selector chain. + // We disallow absolute positions relative to html. + elSelector = processElementSelector(lastOperator, i, false); + if (!elSelector || (isChild && /^html/i.test(elSelector))) { + return; } - classId = ''; - while (start < end) { - tok = selectors[start]; - if (tok.charAt(0) === '#') { - if (/^#_|__$|[^#0-9A-Za-z:_\-]/.test(tok)) { return null; } - // Rewrite ID elements to include the suffix. - classId += tok + '-' + suffix; - } else if (tok === '.') { - if (++start < end - && /^[0-9A-Za-z:_\-]+$/.test(tok = selectors[start]) - && !/^_|__$/.test(tok)) { - classId += '.' + tok; - } else { - return null; - } - } else { - break; - } + lastOperator = i+1; + out.push(elSelector, isChild ? ' > ' : ' '); + } + } + elSelector = processElementSelector(lastOperator, end, true); + if (!elSelector) { return; } + out.push(elSelector); + + function processElementSelector(start, end, last) { + + // Split the element selector into three parts. + // DIV.foo#bar:hover + // ^ ^ + // el classes pseudo + var element, classId, pseudoSelector, tok, elType; + element = ''; + if (start < end) { + tok = selectors[start].toLowerCase(); + if (tok === '*' + || (tok === 'body' && start+1 !== end && !last) + || ('number' === typeof (elType = html4.ELEMENTS[tok]) + && !(elType & html4.eflags.UNSAFE))) { ++start; + element = tok; } - pseudoSelector = ''; - if (start < end && selectors[start] === ':') { - tok = selectors[++start]; - if (tok === 'visited' || tok === 'link') { - if (!/^[a*]?$/.test(element)) { - return null; - } - historySensitive = true; - pseudoSelector = ':' + tok; - element = 'a'; - ++start; + } + classId = ''; + while (start < end) { + tok = selectors[start]; + if (tok.charAt(0) === '#') { + if (/^#_|__$|[^#0-9A-Za-z:_\-]/.test(tok)) { return null; } + // Rewrite ID elements to include the suffix. + classId += tok + '-' + suffix; + } else if (tok === '.') { + if (++start < end + && /^[0-9A-Za-z:_\-]+$/.test(tok = selectors[start]) + && !/^_|__$/.test(tok)) { + classId += '.' + tok; + } else { + return null; } + } else { + break; } - if (start === end) { - return element + classId + pseudoSelector; + ++start; + } + pseudoSelector = ''; + if (start < end && selectors[start] === ':') { + tok = selectors[++start]; + if (tok === 'visited' || tok === 'link') { + if (!/^[a*]?$/.test(element)) { + return null; + } + historySensitive = true; + pseudoSelector = ':' + tok; + element = 'a'; + ++start; } - return null; } - - - var safeSelector = out.join(''); - if (/^body\b/.test(safeSelector)) { - // Substitute the class that is attached to pseudo body elements for - // the body element. - safeSelector = '.vdoc-body___.' + suffix + safeSelector.substring(4); - } else { - // Namespace the selector so that it only matches under - // a node with suffix in its CLASS attribute. - safeSelector = '.' + suffix + ' ' + safeSelector; + if (start === end) { + return element + classId + pseudoSelector; } + return null; + } + - (historySensitive - ? historySensitiveSelectors - : historyInsensitiveSelectors).push(safeSelector); + var safeSelector = out.join(''); + if (/^body\b/.test(safeSelector)) { + // Substitute the class that is attached to pseudo body elements for + // the body element. + safeSelector = '.vdoc-body___.' + suffix + safeSelector.substring(4); + } else { + // Namespace the selector so that it only matches under + // a node with suffix in its CLASS attribute. + safeSelector = '.' + suffix + ' ' + safeSelector; } - return [historyInsensitiveSelectors, historySensitiveSelectors]; + (historySensitive + ? historySensitiveSelectors + : historyInsensitiveSelectors).push(safeSelector); } - var sanitizeStylesheet = (function () { - var allowed = {}; - var cssMediaTypeWhitelist = { - 'braille': allowed, - 'embossed': allowed, - 'handheld': allowed, - 'print': allowed, - 'projection': allowed, - 'screen': allowed, - 'speech': allowed, - 'tty': allowed, - 'tv': allowed - }; + return [historyInsensitiveSelectors, historySensitiveSelectors]; + } - /** - * Given a series of sanitized tokens, removes any properties that would - * leak user history if allowed to style links differently depending on - * whether the linked URL is in the user's browser history. - * @param {Array.} blockOfProperties - */ - function sanitizeHistorySensitive(blockOfProperties) { - var elide = false; - for (var i = 0, n = blockOfProperties.length; i < n-1; ++i) { - var token = blockOfProperties[i]; - if (':' === blockOfProperties[i+1]) { - elide = !(cssSchema[token].cssPropBits & CSS_PROP_BIT_ALLOWED_IN_LINK); - } - if (elide) { blockOfProperties[i] = ''; } - if (';' === token) { elide = false; } + var sanitizeStylesheet = (function () { + var allowed = {}; + var cssMediaTypeWhitelist = { + 'braille': allowed, + 'embossed': allowed, + 'handheld': allowed, + 'print': allowed, + 'projection': allowed, + 'screen': allowed, + 'speech': allowed, + 'tty': allowed, + 'tv': allowed + }; + + /** + * Given a series of sanitized tokens, removes any properties that would + * leak user history if allowed to style links differently depending on + * whether the linked URL is in the user's browser history. + * @param {Array.} blockOfProperties + */ + function sanitizeHistorySensitive(blockOfProperties) { + var elide = false; + for (var i = 0, n = blockOfProperties.length; i < n-1; ++i) { + var token = blockOfProperties[i]; + if (':' === blockOfProperties[i+1]) { + elide = !(cssSchema[token].cssPropBits & CSS_PROP_BIT_ALLOWED_IN_LINK); } - return blockOfProperties.join(''); + if (elide) { blockOfProperties[i] = ''; } + if (';' === token) { elide = false; } } + return blockOfProperties.join(''); + } - /** - * @param {string} cssText a string containing a CSS stylesheet. - * @param {string} suffix a suffix that is added to all IDs and which is - * used as a CLASS names so that the returned selectors will only match - * nodes under one with suffix as a class name. - * If suffix is {@code "sfx"}, the selector - * {@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to - * {@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}. - * @param {function(string, string)} opt_naiveUriRewriter maps URLs of media - * (images, sounds) that appear as CSS property values to sanitized - * URLs or null if the URL should not be allowed as an external media - * file in sanitized CSS. - */ - return function /*sanitizeStylesheet*/( - cssText, suffix, opt_naiveUriRewriter) { - var safeCss = void 0; - // A stack describing the { ... } regions. - // Null elements indicate blocks that should not be emitted. - var blockStack = []; - // True when the content of the current block should be left off safeCss. - var elide = false; - parseCssStylesheet( - cssText, - { - startStylesheet: function () { - safeCss = []; - }, - endStylesheet: function () { - }, - startAtrule: function (atIdent, headerArray) { - if (elide) { - atIdent = null; - } else if (atIdent === '@media') { - headerArray = headerArray.filter( - function (mediaType) { - return cssMediaTypeWhitelist[mediaType] == allowed; - }); - if (headerArray.length) { - safeCss.push(atIdent, headerArray.join(','), '{'); - } else { - atIdent = null; - } + /** + * @param {string} cssText a string containing a CSS stylesheet. + * @param {string} suffix a suffix that is added to all IDs and which is + * used as a CLASS names so that the returned selectors will only match + * nodes under one with suffix as a class name. + * If suffix is {@code "sfx"}, the selector + * {@code ["a", "#foo", " ", "b", ".bar"]} will be namespaced to + * {@code [".sfx", " ", "a", "#foo-sfx", " ", "b", ".bar"]}. + * @param {function(string, string)} opt_naiveUriRewriter maps URLs of media + * (images, sounds) that appear as CSS property values to sanitized + * URLs or null if the URL should not be allowed as an external media + * file in sanitized CSS. + */ + return function /*sanitizeStylesheet*/( + cssText, suffix, opt_naiveUriRewriter) { + var safeCss = void 0; + // A stack describing the { ... } regions. + // Null elements indicate blocks that should not be emitted. + var blockStack = []; + // True when the content of the current block should be left off safeCss. + var elide = false; + parseCssStylesheet( + cssText, + { + startStylesheet: function () { + safeCss = []; + }, + endStylesheet: function () { + }, + startAtrule: function (atIdent, headerArray) { + if (elide) { + atIdent = null; + } else if (atIdent === '@media') { + headerArray = headerArray.filter( + function (mediaType) { + return cssMediaTypeWhitelist[mediaType] == allowed; + }); + if (headerArray.length) { + safeCss.push(atIdent, headerArray.join(','), '{'); } else { - if (atIdent === '@import') { - // TODO: Use a logger instead. - if (window.console) { - window.console.log( - '@import ' + headerArray.join(' ') + ' elided'); - } - } - atIdent = null; // Elide the block. - } - elide = !atIdent; - blockStack.push(atIdent); - }, - endAtrule: function () { - blockStack.pop(); - if (!elide) { - safeCss.push(';'); - } - checkElide(); - }, - startBlock: function () { - // There are no bare blocks in CSS, so we do not change the - // block stack here, but instead in the events that bracket - // blocks. - if (!elide) { - safeCss.push('{'); - } - }, - endBlock: function () { - if (!elide) { - safeCss.push('}'); - elide = true; // skip any semicolon from endAtRule. + atIdent = null; } - }, - startRuleset: function (selectorArray) { - var historySensitiveSelectors = void 0; - var removeHistoryInsensitiveSelectors = false; - if (!elide) { - var selectors = sanitizeCssSelectors(selectorArray, suffix); - var historyInsensitiveSelectors = selectors[0]; - historySensitiveSelectors = selectors[1]; - if (!historyInsensitiveSelectors.length - && !historySensitiveSelectors.length) { - elide = true; - } else { - var selector = historyInsensitiveSelectors.join(', '); - if (!selector) { - // If we have only history sensitive selectors, - // use an impossible rule so that we can capture the content - // for later processing by - // history insenstive content for use below. - selector = 'head > html'; - removeHistoryInsensitiveSelectors = true; - } - safeCss.push(selector, '{'); + } else { + if (atIdent === '@import') { + // TODO: Use a logger instead. + if (window.console) { + window.console.log( + '@import ' + headerArray.join(' ') + ' elided'); } } - blockStack.push( - elide - ? null - // Sometimes a single list of selectors is split in two, - // div, a:visited - // because we want to allow some properties for DIV that - // we don't want to allow for A:VISITED to avoid leaking - // user history. - // Store the history sensitive selectors and the position - // where the block starts so we can later create a copy - // of the permissive tokens, and filter it to handle the - // history sensitive case. - : { - historySensitiveSelectors: historySensitiveSelectors, - endOfSelectors: safeCss.length - 1, // 1 is open curly - removeHistoryInsensitiveSelectors: - removeHistoryInsensitiveSelectors - }); - }, - endRuleset: function () { - var rules = blockStack.pop(); - var propertiesEnd = safeCss.length; - if (!elide) { - safeCss.push('}'); - if (rules) { - var extraSelectors = rules.historySensitiveSelectors; - if (extraSelectors.length) { - var propertyGroupTokens = safeCss.slice(rules.endOfSelectors); - safeCss.push(extraSelectors.join(', '), - sanitizeHistorySensitive(propertyGroupTokens)); - } + atIdent = null; // Elide the block. + } + elide = !atIdent; + blockStack.push(atIdent); + }, + endAtrule: function () { + blockStack.pop(); + if (!elide) { + safeCss.push(';'); + } + checkElide(); + }, + startBlock: function () { + // There are no bare blocks in CSS, so we do not change the + // block stack here, but instead in the events that bracket + // blocks. + if (!elide) { + safeCss.push('{'); + } + }, + endBlock: function () { + if (!elide) { + safeCss.push('}'); + elide = true; // skip any semicolon from endAtRule. + } + }, + startRuleset: function (selectorArray) { + var historySensitiveSelectors = void 0; + var removeHistoryInsensitiveSelectors = false; + if (!elide) { + var selectors = sanitizeCssSelectors(selectorArray, suffix); + var historyInsensitiveSelectors = selectors[0]; + historySensitiveSelectors = selectors[1]; + if (!historyInsensitiveSelectors.length + && !historySensitiveSelectors.length) { + elide = true; + } else { + var selector = historyInsensitiveSelectors.join(', '); + if (!selector) { + // If we have only history sensitive selectors, + // use an impossible rule so that we can capture the content + // for later processing by + // history insenstive content for use below. + selector = 'head > html'; + removeHistoryInsensitiveSelectors = true; } + safeCss.push(selector, '{'); } - if (rules && rules.removeHistoryInsensitiveSelectors) { - safeCss.splice( - // -1 and +1 account for curly braces. - rules.endOfSelectors - 1, propertiesEnd + 1); + } + blockStack.push( + elide + ? null + // Sometimes a single list of selectors is split in two, + // div, a:visited + // because we want to allow some properties for DIV that + // we don't want to allow for A:VISITED to avoid leaking + // user history. + // Store the history sensitive selectors and the position + // where the block starts so we can later create a copy + // of the permissive tokens, and filter it to handle the + // history sensitive case. + : { + historySensitiveSelectors: historySensitiveSelectors, + endOfSelectors: safeCss.length - 1, // 1 is open curly + removeHistoryInsensitiveSelectors: + removeHistoryInsensitiveSelectors + }); + }, + endRuleset: function () { + var rules = blockStack.pop(); + var propertiesEnd = safeCss.length; + if (!elide) { + safeCss.push('}'); + if (rules) { + var extraSelectors = rules.historySensitiveSelectors; + if (extraSelectors.length) { + var propertyGroupTokens = safeCss.slice(rules.endOfSelectors); + safeCss.push(extraSelectors.join(', '), + sanitizeHistorySensitive(propertyGroupTokens)); + } } - checkElide(); - }, - declaration: function (property, valueArray) { - if (!elide) { - var schema = cssSchema[property]; - if (schema) { - sanitizeCssProperty(property, schema, valueArray, opt_naiveUriRewriter); - if (valueArray.length) { - safeCss.push(property, ':', valueArray.join(' '), ';'); - } + } + if (rules && rules.removeHistoryInsensitiveSelectors) { + safeCss.splice( + // -1 and +1 account for curly braces. + rules.endOfSelectors - 1, propertiesEnd + 1); + } + checkElide(); + }, + declaration: function (property, valueArray) { + if (!elide) { + var schema = cssSchema[property]; + if (schema) { + sanitizeCssProperty(property, schema, valueArray, opt_naiveUriRewriter); + if (valueArray.length) { + safeCss.push(property, ':', valueArray.join(' '), ';'); } } } - }); - function checkElide() { - elide = blockStack.length !== 0 - && blockStack[blockStack.length-1] !== null; - } - return safeCss.join(''); - }; - })(); - - // Exports for closure compiler. - if (typeof window !== 'undefined') { - window['sanitizeCssProperty'] = sanitizeCssProperty; - window['sanitizeCssSelectors'] = sanitizeCssSelectors; - window['sanitizeStylesheet'] = sanitizeStylesheet; - } - // Copyright (C) 2010 Google Inc. - // - // 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. - - /** - * @fileoverview - * Utilities for dealing with CSS source code. - * - * @author mikesamuel@gmail.com - * \@requires lexCss - * \@overrides window - * \@provides parseCssStylesheet, parseCssDeclarations - */ - - /** - * parseCssStylesheet takes a chunk of CSS text and a handler object with - * methods that it calls as below: - *
-     * // At the beginning of a stylesheet.
-     * handler.startStylesheet();
-     *
-     * // For an @foo rule ended by a semicolon: @import "foo.css";
-     * handler.startAtrule('@import', ['"foo.css"']);
-     * handler.endAtrule();
-     *
-     * // For an @foo rule ended with a block. @media print { ... }
-     * handler.startAtrule('@media', ['print']);
-     * handler.startBlock();
-     * // Calls to contents elided.  Probably selectors and declarations as below.
-     * handler.endBlock();
-     * handler.endAtrule();
-     *
-     * // For a ruleset: p.clazz q, s { color: blue; }
-     * handler.startRuleset(['p', '.', 'clazz', ' ', 'q', ',', ' ', 's']);
-     * handler.declaration('color', ['blue']);
-     * handler.endRuleset();
-     *
-     * // At the end of a stylesheet.
-     * handler.endStylesheet();
-     * 
- * When errors are encountered, the parser drops the useless tokens and - * attempts to resume parsing. - * - * @param {string} cssText CSS3 content to parse as a stylesheet. - * @param {Object} handler An object like
{
-     *   startStylesheet: function () { ... },
-     *   endStylesheet: function () { ... },
-     *   startAtrule: function (atIdent, headerArray) { ... },
-     *   endAtrule: function () { ... },
-     *   startBlock: function () { ... },
-     *   endBlock: function () { ... },
-     *   startRuleset: function (selectorArray) { ... },
-     *   endRuleset: function () { ... },
-     *   declaration: function (property, valueArray) { ... },
-     * }
- */ - var parseCssStylesheet; - - /** - * parseCssDeclarations parses a run of declaration productions as seen in the - * body of the HTML5 {@code style} attribute. - * - * @param {string} cssText CSS3 content to parse as a run of declarations. - * @param {Object} handler An object like
{
-     *   declaration: function (property, valueArray) { ... },
-     * }
- */ - var parseCssDeclarations; - - (function () { - // stylesheet : [ CDO | CDC | S | statement ]*; - parseCssStylesheet = function(cssText, handler) { - var toks = lexCss(cssText); - if (handler.startStylesheet) { handler.startStylesheet(); } - for (var i = 0, n = toks.length; i < n;) { - // CDO and CDC ("") are converted to space by the lexer. - i = toks[i] === ' ' ? i+1 : statement(toks, i, n, handler); - } - if (handler.endStylesheet) { handler.endStylesheet(); } - }; - - // statement : ruleset | at-rule; - function statement(toks, i, n, handler) { - if (i < n) { - var tok = toks[i]; - if (tok.charAt(0) === '@') { - return atrule(toks, i, n, handler, true); - } else { - return ruleset(toks, i, n, handler); - } + } + }); + function checkElide() { + elide = blockStack.length !== 0 + && blockStack[blockStack.length-1] !== null; + } + return safeCss.join(''); + }; + })(); + + // Exports for closure compiler. + if (typeof window !== 'undefined') { + window['sanitizeCssProperty'] = sanitizeCssProperty; + window['sanitizeCssSelectors'] = sanitizeCssSelectors; + window['sanitizeStylesheet'] = sanitizeStylesheet; + } + // Copyright (C) 2010 Google Inc. + // + // 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. + + /** + * @fileoverview + * Utilities for dealing with CSS source code. + * + * @author mikesamuel@gmail.com + * \@requires lexCss + * \@overrides window + * \@provides parseCssStylesheet, parseCssDeclarations + */ + + /** + * parseCssStylesheet takes a chunk of CSS text and a handler object with + * methods that it calls as below: + *
+   * // At the beginning of a stylesheet.
+   * handler.startStylesheet();
+   *
+   * // For an @foo rule ended by a semicolon: @import "foo.css";
+   * handler.startAtrule('@import', ['"foo.css"']);
+   * handler.endAtrule();
+   *
+   * // For an @foo rule ended with a block. @media print { ... }
+   * handler.startAtrule('@media', ['print']);
+   * handler.startBlock();
+   * // Calls to contents elided.  Probably selectors and declarations as below.
+   * handler.endBlock();
+   * handler.endAtrule();
+   *
+   * // For a ruleset: p.clazz q, s { color: blue; }
+   * handler.startRuleset(['p', '.', 'clazz', ' ', 'q', ',', ' ', 's']);
+   * handler.declaration('color', ['blue']);
+   * handler.endRuleset();
+   *
+   * // At the end of a stylesheet.
+   * handler.endStylesheet();
+   * 
+ * When errors are encountered, the parser drops the useless tokens and + * attempts to resume parsing. + * + * @param {string} cssText CSS3 content to parse as a stylesheet. + * @param {Object} handler An object like
{
+   *   startStylesheet: function () { ... },
+   *   endStylesheet: function () { ... },
+   *   startAtrule: function (atIdent, headerArray) { ... },
+   *   endAtrule: function () { ... },
+   *   startBlock: function () { ... },
+   *   endBlock: function () { ... },
+   *   startRuleset: function (selectorArray) { ... },
+   *   endRuleset: function () { ... },
+   *   declaration: function (property, valueArray) { ... },
+   * }
+ */ + var parseCssStylesheet; + + /** + * parseCssDeclarations parses a run of declaration productions as seen in the + * body of the HTML5 {@code style} attribute. + * + * @param {string} cssText CSS3 content to parse as a run of declarations. + * @param {Object} handler An object like
{
+   *   declaration: function (property, valueArray) { ... },
+   * }
+ */ + var parseCssDeclarations; + + (function () { + // stylesheet : [ CDO | CDC | S | statement ]*; + parseCssStylesheet = function(cssText, handler) { + var toks = lexCss(cssText); + if (handler.startStylesheet) { handler.startStylesheet(); } + for (var i = 0, n = toks.length; i < n;) { + // CDO and CDC ("") are converted to space by the lexer. + i = toks[i] === ' ' ? i+1 : statement(toks, i, n, handler); + } + if (handler.endStylesheet) { handler.endStylesheet(); } + }; + + // statement : ruleset | at-rule; + function statement(toks, i, n, handler) { + if (i < n) { + var tok = toks[i]; + if (tok.charAt(0) === '@') { + return atrule(toks, i, n, handler, true); } else { - return i; - } - } - - // at-rule : ATKEYWORD S* any* [ block | ';' S* ]; - function atrule(toks, i, n, handler, blockok) { - var start = i++; - while (i < n && toks[i] !== '{' && toks[i] !== ';') { - ++i; - } - if (i < n && (blockok || toks[i] === ';')) { - var s = start+1, e = i; - if (s < n && toks[s] === ' ') { ++s; } - if (e > s && toks[e-1] === ' ') { --e; } - if (handler.startAtrule) { - handler.startAtrule(toks[start].toLowerCase(), toks.slice(s, e)); - } - i = (toks[i] === '{') - ? block(toks, i, n, handler) - : i+1; // Skip over ';' - if (handler.endAtrule) { - handler.endAtrule(); - } + return ruleset(toks, i, n, handler); } - // Else we reached end of input or are missing a semicolon. - // Drop the rule on the floor. + } else { return i; } + } - // block : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*; - // Assumes the leading '{' has been verified by callers. - function block(toks, i, n, handler) { - ++i; // skip over '{' - if (handler.startBlock) { handler.startBlock(); } - while (i < n) { - var ch = toks[i].charAt(0); - if (ch == '}') { - ++i; - break; - } - if (ch === ' ' || ch === ';') { - i = i+1; - } else if (ch === '@') { - i = atrule(toks, i, n, handler, false); - } else if (ch === '{') { - i = block(toks, i, n, handler); - } else { - // Instead of using (any* block) to subsume ruleset we allow either - // blocks or rulesets with a non-blank selector. - // This is more restrictive but does not require atrule specific - // parse tree fixup to realize that the contents of the block in - // @media print { ... } - // is a ruleset. We just don't care about any block carrying at-rules - // whose body content is not ruleset content. - i = ruleset(toks, i, n, handler); - } - } - if (handler.endBlock) { handler.endBlock(); } - return i; + // at-rule : ATKEYWORD S* any* [ block | ';' S* ]; + function atrule(toks, i, n, handler, blockok) { + var start = i++; + while (i < n && toks[i] !== '{' && toks[i] !== ';') { + ++i; } - - // ruleset : selector? '{' S* declaration? [ ';' S* declaration? ]* '}' S*; - function ruleset(toks, i, n, handler) { - // toks[s:e] are the selector tokens including internal whitespace. - var s = i, e = selector(toks, i, n, true); - if (e < 0) { - // Skip malformed content per selector calling convention. - e = ~e; - // Make sure we skip at least one token. - return i === e ? e+1 : e; - } - i = e; - // Don't include any trailing space in the selector slice. + if (i < n && (blockok || toks[i] === ';')) { + var s = start+1, e = i; + if (s < n && toks[s] === ' ') { ++s; } if (e > s && toks[e-1] === ' ') { --e; } - var tok = toks[i]; - ++i; // Skip over '{' - if (tok !== '{') { - // Skips past the '{' when there is a malformed input. - return i; - } - if (handler.startRuleset) { - handler.startRuleset(toks.slice(s, e)); - } - while (i < n) { - tok = toks[i]; - if (tok === '}') { - ++i; - break; - } - if (tok === ' ') { - i = i+1; - } else { - i = declaration(toks, i, n, handler); - } + if (handler.startAtrule) { + handler.startAtrule(toks[start].toLowerCase(), toks.slice(s, e)); } - if (handler.endRuleset) { - handler.endRuleset(); + i = (toks[i] === '{') + ? block(toks, i, n, handler) + : i+1; // Skip over ';' + if (handler.endAtrule) { + handler.endAtrule(); } - return i < n ? i+1 : i; } + // Else we reached end of input or are missing a semicolon. + // Drop the rule on the floor. + return i; + } - // selector : any+; - // any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING - // | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES - // | FUNCTION S* any* ')' | DASHMATCH | '(' S* any* ')' - // | '[' S* any* ']' ] S*; - // A negative return value, rv, indicates the selector was malformed and - // the index at which we stopped is ~rv. - function selector(toks, i, n, allowSemi) { - // The definition of any above can be summed up as - // "any run of token except ('[', ']', '(', ')', ':', ';', '{', '}') - // or nested runs of parenthesized tokens or square bracketed tokens". - // Spaces are significant in the selector. - // Selector is used as (selector?) so the below looks for (any*) for - // simplicity. - var tok; - // Keeping a stack pointer actually causes this to minify better since - // ".length" and ".push" are a lo of chars. - var brackets = [], stackLast = -1; - for (;i < n; ++i) { - tok = toks[i].charAt(0); - if (tok === '[' || tok === '(') { - brackets[++stackLast] = tok; - } else if ((tok === ']' && brackets[stackLast] === '[') || - (tok === ')' && brackets[stackLast] === '(')) { - --stackLast; - } else if (tok === '{' || tok === '}' || tok === ';' || tok === '@' - || (tok === ':' && !allowSemi)) { - break; - } - } - if (stackLast >= 0) { - // Returns the bitwise inverse of i+1 to indicate an error in the - // token stream so that clients can ignore it. - i = ~(i+1); - } + // block : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*; + // Assumes the leading '{' has been verified by callers. + function block(toks, i, n, handler) { + ++i; // skip over '{' + if (handler.startBlock) { handler.startBlock(); } + while (i < n) { + var ch = toks[i].charAt(0); + if (ch == '}') { + ++i; + break; + } + if (ch === ' ' || ch === ';') { + i = i+1; + } else if (ch === '@') { + i = atrule(toks, i, n, handler, false); + } else if (ch === '{') { + i = block(toks, i, n, handler); + } else { + // Instead of using (any* block) to subsume ruleset we allow either + // blocks or rulesets with a non-blank selector. + // This is more restrictive but does not require atrule specific + // parse tree fixup to realize that the contents of the block in + // @media print { ... } + // is a ruleset. We just don't care about any block carrying at-rules + // whose body content is not ruleset content. + i = ruleset(toks, i, n, handler); + } + } + if (handler.endBlock) { handler.endBlock(); } + return i; + } + + // ruleset : selector? '{' S* declaration? [ ';' S* declaration? ]* '}' S*; + function ruleset(toks, i, n, handler) { + // toks[s:e] are the selector tokens including internal whitespace. + var s = i, e = selector(toks, i, n, true); + if (e < 0) { + // Skip malformed content per selector calling convention. + e = ~e; + // Make sure we skip at least one token. + return i === e ? e+1 : e; + } + i = e; + // Don't include any trailing space in the selector slice. + if (e > s && toks[e-1] === ' ') { --e; } + var tok = toks[i]; + ++i; // Skip over '{' + if (tok !== '{') { + // Skips past the '{' when there is a malformed input. return i; } - - var ident = /^-?[a-z]/i; - - // declaration : property ':' S* value; - // property : IDENT S*; - // value : [ any | block | ATKEYWORD S* ]+; - function declaration(toks, i, n, handler) { - var property = toks[i++]; - if (!ident.test(property)) { - return i+1; // skip one token. - } - var tok; - if (i < n && toks[i] === ' ') { ++i; } - if (i == n || toks[i] !== ':') { - // skip tokens to next semi or close bracket. - while (i < n && (tok = toks[i]) !== ';' && tok !== '}') { ++i; } - return i; + if (handler.startRuleset) { + handler.startRuleset(toks.slice(s, e)); + } + while (i < n) { + tok = toks[i]; + if (tok === '}') { + ++i; + break; } - ++i; - if (i < n && toks[i] === ' ') { ++i; } - - // None of the rules we care about want atrules or blocks in value, so - // we look for any+ but that is the same as selector but not zero-length. - // This gets us the benefit of not emitting any value with mismatched - // brackets. - var s = i, e = selector(toks, i, n, false); - if (e < 0) { - // Skip malformed content per selector calling convention. - e = ~e; + if (tok === ' ') { + i = i+1; } else { - var value = [], valuelen = 0; - for (var j = s; j < e; ++j) { - tok = toks[j]; - if (tok !== ' ') { - value[valuelen++] = tok; - } - } - // One of the following is now true: - // (1) e is flush with the end of the tokens as in <... style="x:y">. - // (2) tok[e] points to a ';' in which case we need to consume the semi. - // (3) tok[e] points to a '}' in which case we don't consume it. - // (4) else there is bogus unparsed value content at toks[e:]. - // Allow declaration flush with end for style attr body. - if (e < n) { // 2, 3, or 4 - do { - tok = toks[e]; - if (tok === ';' || tok === '}') { break; } - // Don't emit the property if there is questionable trailing content. - valuelen = 0; - } while (++e < n); - if (tok === ';') { - ++e; - } - } - if (valuelen && handler.declaration) { - // TODO: coerce non-keyword ident tokens to quoted strings. - handler.declaration(property.toLowerCase(), value); - } + i = declaration(toks, i, n, handler); } - return e; } - - parseCssDeclarations = function(cssText, handler) { - var toks = lexCss(cssText); - for (var i = 0, n = toks.length; i < n;) { - i = toks[i] !== ' ' ? declaration(toks, i, n, handler) : i+1; - } - }; - })(); - - // Exports for closure compiler. - if (typeof window !== 'undefined') { - window['parseCssStylesheet'] = parseCssStylesheet; - window['parseCssDeclarations'] = parseCssDeclarations; + if (handler.endRuleset) { + handler.endRuleset(); + } + return i < n ? i+1 : i; } - /*! - * OpenUI5 - * (c) Copyright 2009-2024 SAP SE or an SAP affiliate company. - * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. - */ - // Based on coding from the HTML4 Sanitizer by Google Inc. - // The HTML Attributes and ELements were reorganized according to the actual HTML5 specification - // from the W3C. All types and flags were reviewed again as accurately as possible with HTML4 only - // elements removed, you can still see them as comments. All rules which are new or changed from the - // old HTML4 file are also marked "new" within the comment. The comments also state which attributes - // and elements are assigned to respective types and flags. All rules which were not 100% clear were - // analyzed in a way of similarity, so for example "audio" and "video" content behaves like images etc. - // URIEFFECTS state if a URL is loaded inplace within a tag where the actual document is in control - // of what type of content is loaded like "image" or if a new document is loaded like with "a href". - // LOADERTYPES state if content is loaded as sandboxed which means it is loaded within a specific - // surroundig player like with video content for example or if it is loaded freely without restrictions. - // @overrides window - // @provides html4 - - var html4 = {}; - html4.atype = { - NONE: 0, - URI: 1, //action, cite, data, href, icon, manifest, poster, src - URI_FRAGMENT: 11, //usemap - SCRIPT: 2, //all event handlers - STYLE: 3, //style - ID: 4, //id - IDREF: 5, //for - IDREFS: 6, //headers - GLOBAL_NAME: 7, //name of form, iframe, img, map, meta - LOCAL_NAME: 8, //name of button, fieldset, input, keygen, object, output, param, select, textarea - CLASSES: 9, //class - FRAME_TARGET: 10 //formtarget, srcdoc, target - }; - - html4.ATTRIBS = { - '*::accesskey': 0, //NONE - '*::class': 9, //CLASSES - '*::contenteditable': 0, //NONE new - '*::contextmenu': 0, //NONE new - '*::dir': 0, //NONE - '*::draggable': 0, //NONE new - '*::dropzone': 0, //NONE new - '*::hidden': 0, //NONE new - '*::id': 4, //ID - '*::lang': 0, //NONE - '*::onabort': 2, //SCRIPT new - '*::onblur': 2, //SCRIPT new - '*::oncanplay': 2, //SCRIPT new - '*::oncanplaythrough': 2, //SCRIPT new - '*::onchange': 2, //SCRIPT new - '*::onclick': 2, //SCRIPT - '*::oncontextmenu': 2, //SCRIPT new - '*::oncuechange': 2, //SCRIPT new - '*::ondblclick': 2, //SCRIPT - '*::ondrag': 2, //SCRIPT new - '*::ondragend': 2, //SCRIPT new - '*::ondragenter': 2, //SCRIPT new - '*::ondragleave': 2, //SCRIPT new - '*::ondragover': 2, //SCRIPT new - '*::ondragstart': 2, //SCRIPT new - '*::ondrop': 2, //SCRIPT new - '*::ondurationchange': 2, //SCRIPT new - '*::onemptied': 2, //SCRIPT new - '*::onended': 2, //SCRIPT new - '*::onerror': 2, //SCRIPT new - '*::onfocus': 2, //SCRIPT new - '*::oninput': 2, //SCRIPT new - '*::oninvalid': 2, //SCRIPT new - '*::onkeydown': 2, //SCRIPT - '*::onkeypress': 2, //SCRIPT - '*::onkeyup': 2, //SCRIPT - '*::onload': 2, //SCRIPT - '*::onloadeddata': 2, //SCRIPT new - '*::onloadedmetadata': 2, //SCRIPT new - '*::onloadstart': 2, //SCRIPT new - '*::onmousedown': 2, //SCRIPT - '*::onmousemove': 2, //SCRIPT - '*::onmouseout': 2, //SCRIPT - '*::onmouseover': 2, //SCRIPT - '*::onmouseup': 2, //SCRIPT - '*::onmousewheel': 2, //SCRIPT new - '*::onpause': 2, //SCRIPT new - '*::onplay': 2, //SCRIPT new - '*::onplaying': 2, //SCRIPT new - '*::onprogress': 2, //SCRIPT new - '*::onratechange': 2, //SCRIPT new - '*::onreadystatechange': 2, //SCRIPT new - '*::onreset': 2, //SCRIPT new - '*::onscroll': 2, //SCRIPT new - '*::onseeked': 2, //SCRIPT new - '*::onseeking': 2, //SCRIPT new - '*::onselect': 2, //SCRIPT new - '*::onshow': 2, //SCRIPT new - '*::onstalled': 2, //SCRIPT new - '*::onsubmit': 2, //SCRIPT new - '*::onsuspend': 2, //SCRIPT new - '*::ontimeupdate': 2, //SCRIPT new - '*::onvolumechange': 2, //SCRIPT new - '*::onwaiting': 2, //SCRIPT new - '*::spellcheck': 0, //NONE new - '*::style': 3, //STYLE - '*::tabindex': 0, //NONE - '*::title': 0, //NONE - //--------------------- 'a::accesskey': 0, moved to global - //--------------------- 'a::coords': 0, - 'a::href': 1, //URI - 'a::hreflang': 0, //NONE - 'a::media': 0, //NONE new - //--------------------- 'a::name': 7, - //--------------------- 'a::onblur': 2, moved to global - //--------------------- 'a::onfocus': 2, moved to global - 'a::rel': 0, //NONE - //--------------------- 'a::rev': 0, - //--------------------- 'a::shape': 0, - //--------------------- 'a::tabindex': 0, moved to global - 'a::target': 0, //changed to "0" because of CSN 1918585 2013, original value was 10 FRAME_TARGET but it seems uncritical - 'a::type': 0, //NONE - //--------------------- 'area::accesskey': 0, moved to global - 'area::alt': 0, //NONE - 'area::coords': 0, //NONE - 'area::href': 1, //URI - 'area::hreflang': 0, //NONE new - 'area::media': 0, //NONE new - //--------------------- 'area::nohref': 0, - //--------------------- 'area::onblur': 2, moved to global - //--------------------- 'area::onfocus': 2, moved to global - 'area::rel': 0, //NONE new - 'area::shape': 0, //NONE - //--------------------- 'area::tabindex': 0, moved to global - 'area::target': 10, //FRAME_TARGET - 'area::type': 0, //NONE - 'audio::autoplay': 0, //NONE new - 'audio::controls': 0, //NONE new - 'audio::loop': 0, //NONE new - 'audio::mediagroup': 0, //NONE new - 'audio::preload': 0, //NONE new - 'audio::src': 1, //URI - 'base::href': 1, //URI - 'base::target': 10, //FRAME_TARGET - //--------------------- 'bdo::dir': 0, - 'blockquote::cite': 1, //URI - 'body::onafterprint': 2, //SCRIPT new - 'body::onbeforeprint': 2, //SCRIPT new - 'body::onbeforeunload': 2, //SCRIPT new - 'body::onblur': 2, //SCRIPT new - 'body::onerror': 2, //SCRIPT new - 'body::onfocus': 2, //SCRIPT new - 'body::onhashchange': 2, //SCRIPT new - 'body::onload': 2, //SCRIPT new - 'body::onmessage': 2, //SCRIPT new - 'body::onoffline': 2, //SCRIPT new - 'body::ononline': 2, //SCRIPT new - 'body::onpagehide': 2, //SCRIPT new - 'body::onpageshow': 2, //SCRIPT new - 'body::onpopstate': 2, //SCRIPT new - 'body::onredo': 2, //SCRIPT new - 'body::onresize': 2, //SCRIPT new - 'body::onscroll': 2, //SCRIPT new - 'body::onstorage': 2, //SCRIPT new - 'body::onundo': 2, //SCRIPT new - 'body::onunload': 2, //SCRIPT new - //--------------------- 'br::clear': 0, - //--------------------- 'button::accesskey': 0, moved to global - 'button::autofocus': 0, //NONE new - 'button::disabled': 0, //NONE - 'button::form': 0, //NONE new - 'button::formaction': 1, //URI new - 'button::formenctype': 0, //NONE new - 'button::formmethod': 0, //NONE new - 'button::formnovalidate': 0, //NONE new - 'button::formtarget': 10, //FRAME_TARGET new - 'button::name': 8, //LOCAL_NAME - //--------------------- 'button::onblur': 2, - //--------------------- 'button::onfocus': 2, - //--------------------- 'button::tabindex': 0, moved to global - 'button::type': 0, //NONE - 'button::value': 0, //NONE - 'canvas::height': 0, //NONE - 'canvas::width': 0, //NONE - //--------------------- 'caption::align': 0, - //--------------------- 'col::align': 0, - //--------------------- 'col::char': 0, - //--------------------- 'col::charoff': 0, - 'col::span': 0, //NONE - //--------------------- 'col::valign': 0, - //--------------------- 'col::width': 0, - //--------------------- 'colgroup::align': 0, - //--------------------- 'colgroup::char': 0, - //--------------------- 'colgroup::charoff': 0, - 'colgroup::span': 0, //NONE - //--------------------- 'colgroup::valign': 0, - //--------------------- 'colgroup::width': 0, - 'command::checked': 0, //NONE new - 'command::disabled': 0, //NONE new - 'command::icon': 1, //URI new - 'command::label': 0, //NONE new - 'command::radiogroup': 0, //NONE new - 'command::type': 0, //NONE new - 'del::cite': 1, //URI - 'del::datetime': 0, //NONE - 'details::open': 0, //NONE new - //--------------------- 'dir::compact': 0, - //--------------------- 'div::align': 0, - //--------------------- 'dl::compact': 0, - 'embed::height': 0, //NONE new - 'embed::src': 1, //URI new - 'embed::type': 0, //NONE new - 'embed::width': 0, //NONE new - 'fieldset::disabled': 0, //NONE new - 'fieldset::form': 0, //NONE new - 'fieldset::name': 8, //LOCAL_NAME new - //--------------------- 'font::color': 0, - //--------------------- 'font::face': 0, - //--------------------- 'font::size': 0, - //--------------------- 'form::accept': 0, - 'form::accept-charset': 0, //NONE - 'form::action': 1, //URI - 'form::autocomplete': 0, //NONE - 'form::enctype': 0, //NONE - 'form::method': 0, //NONE - 'form::name': 7, //GLOBAL_NAME - 'form::novalidate': 0, //NONE new - //--------------------- 'form::onreset': 2, - //--------------------- 'form::onsubmit': 2, - 'form::target': 10, //FRAME_TARGET - //--------------------- 'h1::align': 0, - //--------------------- 'h2::align': 0, - //--------------------- 'h3::align': 0, - //--------------------- 'h4::align': 0, - //--------------------- 'h5::align': 0, - //--------------------- 'h6::align': 0, - //--------------------- 'hr::align': 0, - //--------------------- 'hr::noshade': 0, - //--------------------- 'hr::size': 0, - //--------------------- 'hr::width': 0, - 'html:: manifest': 1, //URI new - //--------------------- 'iframe::align': 0, - //--------------------- 'iframe::frameborder': 0, - 'iframe::height': 0, //NONE - //--------------------- 'iframe::marginheight': 0, - //--------------------- 'iframe::marginwidth': 0, - 'iframe::name': 7, //GLOBAL_NAME new - 'iframe::sandbox': 0, //NONE new - 'iframe::seamless': 0, //NONE new - 'iframe::src': 1, //URI new - 'iframe::srcdoc': 10, //FRAME_TARGET new - 'iframe::width': 0, //NONE - //--------------------- 'img::align': 0, - 'img::alt': 0, //NONE - //--------------------- 'img::border': 0, - 'img::height': 0, //NONE - //--------------------- 'img::hspace': 0, - 'img::ismap': 0, //NONE - 'img::name': 7, //GLOBAL_NAME - 'img::src': 1, //URI - 'img::usemap': 11, //URI_FRAGMENT - //--------------------- 'img::vspace': 0, - 'img::width': 0, //NONE - 'input::accept': 0, //NONE - //--------------------- 'input::accesskey': 0, moved to global - //--------------------- 'input::align': 0, - 'input::alt': 0, //NONE - 'input::autocomplete': 0, //NONE - 'input::autofocus': 0, //NONE new - 'input::checked': 0, //NONE - 'input::dirname': 0, //NONE new - 'input::disabled': 0, //NONE - 'input::form': 0, //NONE new - 'input::formaction': 1, //URI new - 'input::formenctype': 0, //NONE new - 'input::formmethod': 0, //NONE new - 'input::formnovalidate': 0, //NONE new - 'input::formtarget': 10, //FRAME_TARGET new - 'input::height': 0, //NONE new - //--------------------- 'input::ismap': 0, - 'input::list': 0, //NONE new - 'input::max': 0, //NONE new - 'input::maxlength': 0, //NONE - 'input::min': 0, //NONE new - 'input::multiple': 0, //NONE new - 'input::name': 8, //LOCAL_NAME - //--------------------- 'input::onblur': 2, - //--------------------- 'input::onchange': 2, - //--------------------- 'input::onfocus': 2, - //--------------------- 'input::onselect': 2, - 'input::pattern': 0, //NONE new - 'input::placeholder': 0, //NONE new - 'input::readonly': 0, //NONE - 'input::required': 0, //NONE new - 'input::step': 0, //NONE new - 'input::size': 0, //NONE - 'input::src': 1, //URI - //--------------------- 'input::tabindex': 0, moved to global - 'input::type': 0, //NONE - //--------------------- 'input::usemap': 11, - 'input::value': 0, //NONE - 'input::width': 0, //NONE new - 'ins::cite': 1, //URI - 'ins::datetime': 0, //NONE - //--------------------- 'label::accesskey': 0, moved to global - 'keygen::autofocus': 0, //NONE new - 'keygen::challenge': 0, //NONE new - 'keygen::disabled': 0, //NONE new - 'keygen::form': 0, //NONE new - 'keygen::keytype': 0, //NONE new - 'keygen::name': 8, //LOCAL_NAME new - 'label::for': 5, //IDREF - 'label::form': 0, //NONE new - //--------------------- 'label::onblur': 2, - //--------------------- 'label::onfocus': 2, - //--------------------- 'legend::accesskey': 0, moved to global - //--------------------- 'legend::align': 0, - //--------------------- 'li::type': 0, - 'link::href': 1, //URI new - 'link::hreflang': 0, //NONE new - 'link::media': 0, //NONE new - 'link::rel': 0, //NONE new - 'link::sizes': 0, //NONE new - 'link::type': 0, //NONE new - 'li::value': 0, //NONE new - 'map::name': 7, //GLOBAL_NAME - //--------------------- 'menu::compact': 0, - 'menu::label': 0, //NONE new - 'menu::type': 0, //NONE new - 'meta::charset': 0, //NONE new - 'meta::content': 0, //NONE new - 'meta::http-equiv': 0, //NONE new - 'meta::name': 7, //GLOBAL_NAME new - 'meter::form': 0, //NONE new - 'meter::high': 0, //NONE new - 'meter::low': 0, //NONE new - 'meter::max': 0, //NONE new - 'meter::min': 0, //NONE new - 'meter::optimum': 0, //NONE new - 'meter::value': 0, //NONE new - 'object::data': 1, //URI new - 'object::form': 0, //NONE new - 'object::height': 0, //NONE new - 'object::name': 8, //LOCAL_NAME new - 'object::type': 0, //NONE new - 'object::usemap': 11, //URI_FRAGMENT new - 'object::width': 0, //NONE new - //--------------------- 'ol::compact': 0, - 'ol::reversed': 0, //NONE new - 'ol::start': 0, //NONE - //--------------------- 'ol::type': 0, - 'optgroup::disabled': 0, //NONE - 'optgroup::label': 0, //NONE - 'option::disabled': 0, //NONE - 'option::label': 0, //NONE - 'option::selected': 0, //NONE - 'option::value': 0, //NONE - 'output::for': 5, //IDREF new - 'output::form': 0, //NONE new - 'output::name': 8, //LOCAL_NAME new - //--------------------- 'p::align': 0, - 'param::name': 8, //LOCAL_NAME new - 'param::value': 0, //NONE new - 'progress::form': 0, //NONE new - 'progress::max': 0, //NONE new - 'progress::value': 0, //NONE new - //--------------------- 'pre::width': 0, - 'q::cite': 1, //URI - 'script::async': 0, //NONE new - 'script::charset': 0, //NONE new - 'script::defer': 0, //NONE new - 'script::src': 1, //URI new - 'script::type': 0, //NONE new - 'select::autofocus': 0, //NONE new - 'select::disabled': 0, //NONE - 'select::form': 0, //NONE new - 'select::multiple': 0, //NONE - 'select::name': 8, //LOCAL_NAME - //--------------------- 'select::onblur': 2, - //--------------------- 'select::onchange': 2, - //--------------------- 'select::onfocus': 2, - 'select::required': 0, //NONE new - 'select::size': 0, //NONE - //--------------------- 'select::tabindex': 0, moved to global - 'source::media': 0, //NONE new - 'source::src': 1, //URI new - 'source::type': 0, //NONE new - 'style::media': 0, //NONE new - 'style::scoped': 0, //NONE new - 'style::type': 0, //NONE new - //--------------------- 'table::align': 0, - //--------------------- 'table::bgcolor': 0, - 'table::border': 0, //NONE - //--------------------- 'table::cellpadding': 0, - //--------------------- 'table::cellspacing': 0, - //--------------------- 'table::frame': 0, - //--------------------- 'table::rules': 0, - //--------------------- 'table::summary': 0, - //--------------------- 'table::width': 0, - //--------------------- 'tbody::align': 0, - //--------------------- 'tbody::char': 0, - //--------------------- 'tbody::charoff': 0, - //--------------------- 'tbody::valign': 0, - //--------------------- 'td::abbr': 0, - //--------------------- 'td::align': 0, - //--------------------- 'td::axis': 0, - //--------------------- 'td::bgcolor': 0, - //--------------------- 'td::char': 0, - //--------------------- 'td::charoff': 0, - 'td::colspan': 0, //NONE - 'td::headers': 6, //IDREFS - //--------------------- 'td::height': 0, - //--------------------- 'td::nowrap': 0, - 'td::rowspan': 0, //NONE - //--------------------- 'td::scope': 0, - //--------------------- 'td::valign': 0, - //--------------------- 'td::width': 0, - //--------------------- 'textarea::accesskey': 0, moved to global - 'textarea::autofocus': 0, //NONE new - 'textarea::cols': 0, //NONE - 'textarea::disabled': 0, //NONE - 'textarea::form': 0, //NONE new - 'textarea::maxlength': 0, //NONE new - 'textarea::name': 8, //LOCAL_NAME - //--------------------- 'textarea::onblur': 2, - //--------------------- 'textarea::onchange': 2, - //--------------------- 'textarea::onfocus': 2, - //--------------------- 'textarea::onselect': 2, - 'textarea::placeholder': 0, //NONE new - 'textarea::readonly': 0, //NONE - 'textarea::required': 0, //NONE new - 'textarea::rows': 0, //NONE - 'textarea::wrap': 0, //NONE new - //--------------------- 'textarea::tabindex': 0, moved to global - //--------------------- 'tfoot::align': 0, - //--------------------- 'tfoot::char': 0, - //--------------------- 'tfoot::charoff': 0, - //--------------------- 'tfoot::valign': 0, - //--------------------- 'th::abbr': 0, - //--------------------- 'th::align': 0, - //--------------------- 'th::axis': 0, - //--------------------- 'th::bgcolor': 0, - //--------------------- 'th::char': 0, - //--------------------- 'th::charoff': 0, - 'th::colspan': 0, //NONE - 'th::headers': 6, //IDREFS - //--------------------- 'th::height': 0, - //--------------------- 'th::nowrap': 0, - 'th::rowspan': 0, //NONE - 'th::scope': 0, //NONE - //--------------------- 'th::valign': 0, - //--------------------- 'th::width': 0, - //--------------------- 'thead::align': 0, - //--------------------- 'thead::char': 0, - //--------------------- 'thead::charoff': 0, - //--------------------- 'thead::valign': 0, - 'time::datetime': 0, //NONE new - 'time::pubdate': 0, //NONE new - //--------------------- 'tr::align': 0, - //--------------------- 'tr::bgcolor': 0, - //--------------------- 'tr::char': 0, - //--------------------- 'tr::charoff': 0, - //--------------------- 'tr::valign': 0, - 'track::default': 0, //NONE new - 'track::kind': 0, //NONE new - 'track::label': 0, //NONE new - 'track::src': 1, //URI new - 'track::srclang': 0, //NONE new - //--------------------- 'ul::compact': 0, - //--------------------- 'ul::type': 0 - 'video::autoplay': 0, //NONE new - 'video::controls': 0, //NONE new - 'video::height': 0, //NONE new - 'video::loop': 0, //NONE new - 'video::mediagroup': 0, //NONE new - 'video::poster': 1, //URI new - 'video::preload': 0, //NONE new - 'video::src': 1, //URI new - 'video::width': 0 //NONE new - }; - html4.eflags = { - OPTIONAL_ENDTAG: 1, - EMPTY: 2, - CDATA: 4, - RCDATA: 8, - UNSAFE: 16, - FOLDABLE: 32, - SCRIPT: 64, - STYLE: 128 - }; - html4.ELEMENTS = { - 'a': 0, - 'abbr': 0, - //--------------------- 'acronym': 0, - 'address': 0, - //--------------------- 'applet': 16, - 'area': 2, //EMPTY - 'article': 0, //new - 'aside': 0, //new - 'audio': 0, //new - 'b': 0, - 'base': 18, //EMPTY, UNSAFE - //--------------------- 'basefont': 18, - 'bdi': 0, //new - 'bdo': 0, - //--------------------- 'big': 0, - 'blockquote': 0, - 'body': 49, //OPTIONAL_ENDTAG, UNSAFE, FOLDABLE - 'br': 2, //EMPTY - 'button': 0, - 'canvas': 0, - 'caption': 0, - //--------------------- 'center': 0, - 'cite': 0, - 'code': 0, - 'col': 2, //EMPTY - 'colgroup': 1, //OPTIONAL_ENDTAG - 'command': 2, //EMPTY new - 'datalist': 0, //new - 'dd': 1, //OPTIONAL_ENDTAG - 'del': 0, - 'details': 0, //new - 'dfn': 0, - //--------------------- 'dir': 0, - 'div': 0, - 'dl': 0, - 'dt': 1, //OPTIONAL_ENDTAG - 'em': 0, - 'embed': 18, //EMPTY, UNSAFE new - 'fieldset': 0, - 'figcaption': 0, //new - 'figure': 0, //new - //--------------------- 'font': 0, - 'footer': 0, //new - 'form': 0, - //--------------------- 'frame': 18, - //--------------------- 'frameset': 16, - 'h1': 0, - 'h2': 0, - 'h3': 0, - 'h4': 0, - 'h5': 0, - 'h6': 0, - 'head': 49, //OPTIONAL_ENDTAG, UNSAFE, FOLDABLE - 'header': 0, //new - 'hgroup': 0, //new - 'hr': 2, //EMPTY - 'html': 49, //OPTIONAL_ENDTAG, UNSAFE, FOLDABLE - 'i': 0, - 'iframe': 0, //new - 'img': 2,//EMPTY - 'input': 2, //EMPTY - 'ins': 0, - //--------------------- 'isindex': 18, - 'kbd': 0, - 'keygen': 2, //EMPTY new - 'label': 0, - 'legend': 0, - 'li': 1, //OPTIONAL_ENDTAG - 'link': 18, //EMPTY, UNSAFE - 'map': 0, - 'mark': 0, //new - 'menu': 0, - 'meta': 18, //EMPTY, UNSAFE - 'meter': 0, //new - 'nav': 0, - //--------------------- 'nobr': 0, - //--------------------- 'noembed': 4, - //--------------------- 'noframes': 20, - 'noscript': 20, //CDATA, UNSAFE - 'object': 16, //UNSAFE - 'ol': 0, - 'optgroup': 1, //OPTIONAL_ENDTAG new !!!!vorher 0 - 'option': 1, //OPTIONAL_ENDTAG - 'output': 0, //new - 'p': 1, //OPTIONAL_ENDTAG - 'param': 18, //EMPTY, UNSAFE - 'pre': 0, - 'progress': 0, //new - 'q': 0, - 'rp': 1, //OPTIONAL_ENDTAG new - 'rt': 1, //OPTIONAL_ENDTAG new - 'ruby': 0, //new - 's': 0, - 'samp': 0, - 'script': 84, //CDATA, UNSAFE, SCRIPT - 'section': 0, //new - 'select': 0, - 'small': 0, - 'source': 2, //EMPTY new - 'span': 0, - //--------------------- 'strike': 0, - 'strong': 0, - 'style': 148, //CDATA, UNSAFE, STYLE - 'sub': 0, - 'summary': 0, //new - 'sup': 0, - 'table': 0, - 'tbody': 1, //OPTIONAL_ENDTAG - 'td': 1, //OPTIONAL_ENDTAG - 'textarea': 8, //RCDATA - 'tfoot': 1, //OPTIONAL_ENDTAG - 'th': 1, //OPTIONAL_ENDTAG - 'thead': 1, //OPTIONAL_ENDTAG - 'time': 0, //new - 'title': 24, //RCDATA, UNSAFE - 'tr': 1, //OPTIONAL_ENDTAG - 'track': 2, //EMPTY new - //--------------------- 'tt': 0, - 'u': 0, - 'ul': 0, - 'var': 0, - 'video': 0, //new - 'wbr': 2 //EMPTY new - }; - html4.ueffects = { - NOT_LOADED: 0, - SAME_DOCUMENT: 1, - NEW_DOCUMENT: 2 - }; - html4.URIEFFECTS = { - 'a::href': 2, //NEW_DOCUMENT - 'area::href': 2, //NEW_DOCUMENT - 'audio::src': 1, //SAME_DOCUMENT new - 'base::href':2, //NEW_DOCUMENT new - 'blockquote::cite': 0, //NOT_LOADED - //--------------------- 'body::background': 1, - 'button::formaction': 2, //NEW_DOCUMENT new - 'command::icon': 1, //SAME_DOCUMENT new - 'del::cite': 0, //NOT_LOADED - 'embed::src': 1, //SAME_DOCUMENT new - 'form::action': 2, //NEW_DOCUMENT - 'html:: manifest': 1, //SAME_DOCUMENT new - 'iframe::src': 1, //SAME_DOCUMENT new - 'img::src': 1, //SAME_DOCUMENT - 'input::formaction': 2, //NEW_DOCUMENT new - 'input::src': 1, //SAME_DOCUMENT - 'ins::cite': 0, //NOT_LOADED - 'link::href': 2, //NEW_DOCUMENT new - 'object::data': 1, //SAME_DOCUMENT new - 'q::cite': 0, //NOT_LOADED - 'script::src': 1, //SAME_DOCUMENT new - 'source::src': 1, //SAME_DOCUMENT new - 'track::src': 1, //SAME_DOCUMENT new - 'video::poster': 1, //SAME_DOCUMENT new - 'video::src': 1 //SAME_DOCUMENT new - }; - html4.ltypes = { - UNSANDBOXED: 2, - SANDBOXED: 1, - DATA: 0 - }; - html4.LOADERTYPES = { - 'a::href': 2, //UNSANDBOXED - 'area::href': 2, //UNSANDBOXED - 'audio::src': 1, //SANDBOXED new - 'base::href': 2, //UNSANDBOXED new - 'blockquote::cite': 2, //UNSANDBOXED - //--------------------- 'body::background': 1, - 'button::formaction': 2, //UNSANDBOXED new - 'command::icon': 1, //SANDBOXED new - 'del::cite': 2, //UNSANDBOXED - 'embed::src': 1, //SANDBOXED new - 'form::action': 2, //UNSANDBOXED - 'html:: manifest': 1, //SANDBOXED new - 'iframe::src': 1, //SANDBOXED new - 'img::src': 1, //SANDBOXED - 'input::formaction': 2, //UNSANDBOXED new - 'input::src': 1, //SANDBOXED - 'ins::cite': 2, //UNSANDBOXED - 'link::href': 2, //UNSANDBOXED new - 'object::data': 0, //DATA new - 'q::cite': 2, //UNSANDBOXED - 'script::src': 1, //SANDBOXED new - 'source::src': 1, //SANDBOXED new - 'track::src': 1, //SANDBOXED new - 'video::poster': 1, //SANDBOXED new - 'video::src': 1 //SANDBOXED new - };if (typeof window !== 'undefined') { - window['html4'] = html4; - }// Copyright (C) 2006 Google Inc. - // - // 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. - /** - * @fileoverview - * An HTML sanitizer that can satisfy a variety of security policies. - * - *

- * The HTML sanitizer is built around a SAX parser and HTML element and - * attributes schemas. - * - * If the cssparser is loaded, inline styles are sanitized using the - * css property and value schemas. Else they are remove during - * sanitization. - * - * If it exists, uses parseCssDeclarations, sanitizeCssProperty, cssSchema - * - * @author mikesamuel@gmail.com - * @author jasvir@gmail.com - * \@requires html4 - * \@overrides window - * \@provides html, html_sanitize - */ + // selector : any+; + // any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING + // | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES + // | FUNCTION S* any* ')' | DASHMATCH | '(' S* any* ')' + // | '[' S* any* ']' ] S*; + // A negative return value, rv, indicates the selector was malformed and + // the index at which we stopped is ~rv. + function selector(toks, i, n, allowSemi) { + // The definition of any above can be summed up as + // "any run of token except ('[', ']', '(', ')', ':', ';', '{', '}') + // or nested runs of parenthesized tokens or square bracketed tokens". + // Spaces are significant in the selector. + // Selector is used as (selector?) so the below looks for (any*) for + // simplicity. + var tok; + // Keeping a stack pointer actually causes this to minify better since + // ".length" and ".push" are a lo of chars. + var brackets = [], stackLast = -1; + for (;i < n; ++i) { + tok = toks[i].charAt(0); + if (tok === '[' || tok === '(') { + brackets[++stackLast] = tok; + } else if ((tok === ']' && brackets[stackLast] === '[') || + (tok === ')' && brackets[stackLast] === '(')) { + --stackLast; + } else if (tok === '{' || tok === '}' || tok === ';' || tok === '@' + || (tok === ':' && !allowSemi)) { + break; + } + } + if (stackLast >= 0) { + // Returns the bitwise inverse of i+1 to indicate an error in the + // token stream so that clients can ignore it. + i = ~(i+1); + } + return i; + } - /** - * \@namespace - */ - var html = (function(html4) { - - // For closure compiler - var parseCssDeclarations, sanitizeCssProperty, cssSchema; - if ('undefined' !== typeof window) { - parseCssDeclarations = window['parseCssDeclarations']; - sanitizeCssProperty = window['sanitizeCssProperty']; - cssSchema = window['cssSchema']; + var ident = /^-?[a-z]/i; + + // declaration : property ':' S* value; + // property : IDENT S*; + // value : [ any | block | ATKEYWORD S* ]+; + function declaration(toks, i, n, handler) { + var property = toks[i++]; + if (!ident.test(property)) { + return i+1; // skip one token. + } + var tok; + if (i < n && toks[i] === ' ') { ++i; } + if (i == n || toks[i] !== ':') { + // skip tokens to next semi or close bracket. + while (i < n && (tok = toks[i]) !== ';' && tok !== '}') { ++i; } + return i; } - - var lcase; - // The below may not be true on browsers in the Turkish locale. - if ('script' === 'SCRIPT'.toLowerCase()) { - lcase = function(s) { return s.toLowerCase(); }; + ++i; + if (i < n && toks[i] === ' ') { ++i; } + + // None of the rules we care about want atrules or blocks in value, so + // we look for any+ but that is the same as selector but not zero-length. + // This gets us the benefit of not emitting any value with mismatched + // brackets. + var s = i, e = selector(toks, i, n, false); + if (e < 0) { + // Skip malformed content per selector calling convention. + e = ~e; } else { - /** - * {\@updoc - * $ lcase('SCRIPT') - * # 'script' - * $ lcase('script') - * # 'script' - * } - */ - lcase = function(s) { - return s.replace( - /[A-Z]/g, - function(ch) { - return String.fromCharCode(ch.charCodeAt(0) | 32); - }); - }; + var value = [], valuelen = 0; + for (var j = s; j < e; ++j) { + tok = toks[j]; + if (tok !== ' ') { + value[valuelen++] = tok; + } + } + // One of the following is now true: + // (1) e is flush with the end of the tokens as in <... style="x:y">. + // (2) tok[e] points to a ';' in which case we need to consume the semi. + // (3) tok[e] points to a '}' in which case we don't consume it. + // (4) else there is bogus unparsed value content at toks[e:]. + // Allow declaration flush with end for style attr body. + if (e < n) { // 2, 3, or 4 + do { + tok = toks[e]; + if (tok === ';' || tok === '}') { break; } + // Don't emit the property if there is questionable trailing content. + valuelen = 0; + } while (++e < n); + if (tok === ';') { + ++e; + } + } + if (valuelen && handler.declaration) { + // TODO: coerce non-keyword ident tokens to quoted strings. + handler.declaration(property.toLowerCase(), value); + } } + return e; + } - // The keys of this object must be 'quoted' or JSCompiler will mangle them! - var ENTITIES = { - 'lt': '<', - 'gt': '>', - 'amp': '&', - 'nbsp': '\xA0', - 'quot': '"', - 'apos': '\'' - }; + parseCssDeclarations = function(cssText, handler) { + var toks = lexCss(cssText); + for (var i = 0, n = toks.length; i < n;) { + i = toks[i] !== ' ' ? declaration(toks, i, n, handler) : i+1; + } + }; + })(); + + // Exports for closure compiler. + if (typeof window !== 'undefined') { + window['parseCssStylesheet'] = parseCssStylesheet; + window['parseCssDeclarations'] = parseCssDeclarations; + } + /*! + * OpenUI5 + * (c) Copyright 2009-2024 SAP SE or an SAP affiliate company. + * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. + */ + // Based on coding from the HTML4 Sanitizer by Google Inc. + // The HTML Attributes and ELements were reorganized according to the actual HTML5 specification + // from the W3C. All types and flags were reviewed again as accurately as possible with HTML4 only + // elements removed, you can still see them as comments. All rules which are new or changed from the + // old HTML4 file are also marked "new" within the comment. The comments also state which attributes + // and elements are assigned to respective types and flags. All rules which were not 100% clear were + // analyzed in a way of similarity, so for example "audio" and "video" content behaves like images etc. + // URIEFFECTS state if a URL is loaded inplace within a tag where the actual document is in control + // of what type of content is loaded like "image" or if a new document is loaded like with "a href". + // LOADERTYPES state if content is loaded as sandboxed which means it is loaded within a specific + // surroundig player like with video content for example or if it is loaded freely without restrictions. + // @overrides window + // @provides html4 + + var html4 = {}; + html4.atype = { + NONE: 0, + URI: 1, //action, cite, data, href, icon, manifest, poster, src + URI_FRAGMENT: 11, //usemap + SCRIPT: 2, //all event handlers + STYLE: 3, //style + ID: 4, //id + IDREF: 5, //for + IDREFS: 6, //headers + GLOBAL_NAME: 7, //name of form, iframe, img, map, meta + LOCAL_NAME: 8, //name of button, fieldset, input, keygen, object, output, param, select, textarea + CLASSES: 9, //class + FRAME_TARGET: 10 //formtarget, srcdoc, target + }; + + html4.ATTRIBS = { + '*::accesskey': 0, //NONE + '*::class': 9, //CLASSES + '*::contenteditable': 0, //NONE new + '*::contextmenu': 0, //NONE new + '*::dir': 0, //NONE + '*::draggable': 0, //NONE new + '*::dropzone': 0, //NONE new + '*::hidden': 0, //NONE new + '*::id': 4, //ID + '*::lang': 0, //NONE + '*::onabort': 2, //SCRIPT new + '*::onblur': 2, //SCRIPT new + '*::oncanplay': 2, //SCRIPT new + '*::oncanplaythrough': 2, //SCRIPT new + '*::onchange': 2, //SCRIPT new + '*::onclick': 2, //SCRIPT + '*::oncontextmenu': 2, //SCRIPT new + '*::oncuechange': 2, //SCRIPT new + '*::ondblclick': 2, //SCRIPT + '*::ondrag': 2, //SCRIPT new + '*::ondragend': 2, //SCRIPT new + '*::ondragenter': 2, //SCRIPT new + '*::ondragleave': 2, //SCRIPT new + '*::ondragover': 2, //SCRIPT new + '*::ondragstart': 2, //SCRIPT new + '*::ondrop': 2, //SCRIPT new + '*::ondurationchange': 2, //SCRIPT new + '*::onemptied': 2, //SCRIPT new + '*::onended': 2, //SCRIPT new + '*::onerror': 2, //SCRIPT new + '*::onfocus': 2, //SCRIPT new + '*::oninput': 2, //SCRIPT new + '*::oninvalid': 2, //SCRIPT new + '*::onkeydown': 2, //SCRIPT + '*::onkeypress': 2, //SCRIPT + '*::onkeyup': 2, //SCRIPT + '*::onload': 2, //SCRIPT + '*::onloadeddata': 2, //SCRIPT new + '*::onloadedmetadata': 2, //SCRIPT new + '*::onloadstart': 2, //SCRIPT new + '*::onmousedown': 2, //SCRIPT + '*::onmousemove': 2, //SCRIPT + '*::onmouseout': 2, //SCRIPT + '*::onmouseover': 2, //SCRIPT + '*::onmouseup': 2, //SCRIPT + '*::onmousewheel': 2, //SCRIPT new + '*::onpause': 2, //SCRIPT new + '*::onplay': 2, //SCRIPT new + '*::onplaying': 2, //SCRIPT new + '*::onprogress': 2, //SCRIPT new + '*::onratechange': 2, //SCRIPT new + '*::onreadystatechange': 2, //SCRIPT new + '*::onreset': 2, //SCRIPT new + '*::onscroll': 2, //SCRIPT new + '*::onseeked': 2, //SCRIPT new + '*::onseeking': 2, //SCRIPT new + '*::onselect': 2, //SCRIPT new + '*::onshow': 2, //SCRIPT new + '*::onstalled': 2, //SCRIPT new + '*::onsubmit': 2, //SCRIPT new + '*::onsuspend': 2, //SCRIPT new + '*::ontimeupdate': 2, //SCRIPT new + '*::onvolumechange': 2, //SCRIPT new + '*::onwaiting': 2, //SCRIPT new + '*::spellcheck': 0, //NONE new + '*::style': 3, //STYLE + '*::tabindex': 0, //NONE + '*::title': 0, //NONE + //--------------------- 'a::accesskey': 0, moved to global + //--------------------- 'a::coords': 0, + 'a::href': 1, //URI + 'a::hreflang': 0, //NONE + 'a::media': 0, //NONE new + //--------------------- 'a::name': 7, + //--------------------- 'a::onblur': 2, moved to global + //--------------------- 'a::onfocus': 2, moved to global + 'a::rel': 0, //NONE + //--------------------- 'a::rev': 0, + //--------------------- 'a::shape': 0, + //--------------------- 'a::tabindex': 0, moved to global + 'a::target': 0, //changed to "0" because of CSN 1918585 2013, original value was 10 FRAME_TARGET but it seems uncritical + 'a::type': 0, //NONE + //--------------------- 'area::accesskey': 0, moved to global + 'area::alt': 0, //NONE + 'area::coords': 0, //NONE + 'area::href': 1, //URI + 'area::hreflang': 0, //NONE new + 'area::media': 0, //NONE new + //--------------------- 'area::nohref': 0, + //--------------------- 'area::onblur': 2, moved to global + //--------------------- 'area::onfocus': 2, moved to global + 'area::rel': 0, //NONE new + 'area::shape': 0, //NONE + //--------------------- 'area::tabindex': 0, moved to global + 'area::target': 10, //FRAME_TARGET + 'area::type': 0, //NONE + 'audio::autoplay': 0, //NONE new + 'audio::controls': 0, //NONE new + 'audio::loop': 0, //NONE new + 'audio::mediagroup': 0, //NONE new + 'audio::preload': 0, //NONE new + 'audio::src': 1, //URI + 'base::href': 1, //URI + 'base::target': 10, //FRAME_TARGET + //--------------------- 'bdo::dir': 0, + 'blockquote::cite': 1, //URI + 'body::onafterprint': 2, //SCRIPT new + 'body::onbeforeprint': 2, //SCRIPT new + 'body::onbeforeunload': 2, //SCRIPT new + 'body::onblur': 2, //SCRIPT new + 'body::onerror': 2, //SCRIPT new + 'body::onfocus': 2, //SCRIPT new + 'body::onhashchange': 2, //SCRIPT new + 'body::onload': 2, //SCRIPT new + 'body::onmessage': 2, //SCRIPT new + 'body::onoffline': 2, //SCRIPT new + 'body::ononline': 2, //SCRIPT new + 'body::onpagehide': 2, //SCRIPT new + 'body::onpageshow': 2, //SCRIPT new + 'body::onpopstate': 2, //SCRIPT new + 'body::onredo': 2, //SCRIPT new + 'body::onresize': 2, //SCRIPT new + 'body::onscroll': 2, //SCRIPT new + 'body::onstorage': 2, //SCRIPT new + 'body::onundo': 2, //SCRIPT new + 'body::onunload': 2, //SCRIPT new + //--------------------- 'br::clear': 0, + //--------------------- 'button::accesskey': 0, moved to global + 'button::autofocus': 0, //NONE new + 'button::disabled': 0, //NONE + 'button::form': 0, //NONE new + 'button::formaction': 1, //URI new + 'button::formenctype': 0, //NONE new + 'button::formmethod': 0, //NONE new + 'button::formnovalidate': 0, //NONE new + 'button::formtarget': 10, //FRAME_TARGET new + 'button::name': 8, //LOCAL_NAME + //--------------------- 'button::onblur': 2, + //--------------------- 'button::onfocus': 2, + //--------------------- 'button::tabindex': 0, moved to global + 'button::type': 0, //NONE + 'button::value': 0, //NONE + 'canvas::height': 0, //NONE + 'canvas::width': 0, //NONE + //--------------------- 'caption::align': 0, + //--------------------- 'col::align': 0, + //--------------------- 'col::char': 0, + //--------------------- 'col::charoff': 0, + 'col::span': 0, //NONE + //--------------------- 'col::valign': 0, + //--------------------- 'col::width': 0, + //--------------------- 'colgroup::align': 0, + //--------------------- 'colgroup::char': 0, + //--------------------- 'colgroup::charoff': 0, + 'colgroup::span': 0, //NONE + //--------------------- 'colgroup::valign': 0, + //--------------------- 'colgroup::width': 0, + 'command::checked': 0, //NONE new + 'command::disabled': 0, //NONE new + 'command::icon': 1, //URI new + 'command::label': 0, //NONE new + 'command::radiogroup': 0, //NONE new + 'command::type': 0, //NONE new + 'del::cite': 1, //URI + 'del::datetime': 0, //NONE + 'details::open': 0, //NONE new + //--------------------- 'dir::compact': 0, + //--------------------- 'div::align': 0, + //--------------------- 'dl::compact': 0, + 'embed::height': 0, //NONE new + 'embed::src': 1, //URI new + 'embed::type': 0, //NONE new + 'embed::width': 0, //NONE new + 'fieldset::disabled': 0, //NONE new + 'fieldset::form': 0, //NONE new + 'fieldset::name': 8, //LOCAL_NAME new + //--------------------- 'font::color': 0, + //--------------------- 'font::face': 0, + //--------------------- 'font::size': 0, + //--------------------- 'form::accept': 0, + 'form::accept-charset': 0, //NONE + 'form::action': 1, //URI + 'form::autocomplete': 0, //NONE + 'form::enctype': 0, //NONE + 'form::method': 0, //NONE + 'form::name': 7, //GLOBAL_NAME + 'form::novalidate': 0, //NONE new + //--------------------- 'form::onreset': 2, + //--------------------- 'form::onsubmit': 2, + 'form::target': 10, //FRAME_TARGET + //--------------------- 'h1::align': 0, + //--------------------- 'h2::align': 0, + //--------------------- 'h3::align': 0, + //--------------------- 'h4::align': 0, + //--------------------- 'h5::align': 0, + //--------------------- 'h6::align': 0, + //--------------------- 'hr::align': 0, + //--------------------- 'hr::noshade': 0, + //--------------------- 'hr::size': 0, + //--------------------- 'hr::width': 0, + 'html:: manifest': 1, //URI new + //--------------------- 'iframe::align': 0, + //--------------------- 'iframe::frameborder': 0, + 'iframe::height': 0, //NONE + //--------------------- 'iframe::marginheight': 0, + //--------------------- 'iframe::marginwidth': 0, + 'iframe::name': 7, //GLOBAL_NAME new + 'iframe::sandbox': 0, //NONE new + 'iframe::seamless': 0, //NONE new + 'iframe::src': 1, //URI new + 'iframe::srcdoc': 10, //FRAME_TARGET new + 'iframe::width': 0, //NONE + //--------------------- 'img::align': 0, + 'img::alt': 0, //NONE + //--------------------- 'img::border': 0, + 'img::height': 0, //NONE + //--------------------- 'img::hspace': 0, + 'img::ismap': 0, //NONE + 'img::name': 7, //GLOBAL_NAME + 'img::src': 1, //URI + 'img::usemap': 11, //URI_FRAGMENT + //--------------------- 'img::vspace': 0, + 'img::width': 0, //NONE + 'input::accept': 0, //NONE + //--------------------- 'input::accesskey': 0, moved to global + //--------------------- 'input::align': 0, + 'input::alt': 0, //NONE + 'input::autocomplete': 0, //NONE + 'input::autofocus': 0, //NONE new + 'input::checked': 0, //NONE + 'input::dirname': 0, //NONE new + 'input::disabled': 0, //NONE + 'input::form': 0, //NONE new + 'input::formaction': 1, //URI new + 'input::formenctype': 0, //NONE new + 'input::formmethod': 0, //NONE new + 'input::formnovalidate': 0, //NONE new + 'input::formtarget': 10, //FRAME_TARGET new + 'input::height': 0, //NONE new + //--------------------- 'input::ismap': 0, + 'input::list': 0, //NONE new + 'input::max': 0, //NONE new + 'input::maxlength': 0, //NONE + 'input::min': 0, //NONE new + 'input::multiple': 0, //NONE new + 'input::name': 8, //LOCAL_NAME + //--------------------- 'input::onblur': 2, + //--------------------- 'input::onchange': 2, + //--------------------- 'input::onfocus': 2, + //--------------------- 'input::onselect': 2, + 'input::pattern': 0, //NONE new + 'input::placeholder': 0, //NONE new + 'input::readonly': 0, //NONE + 'input::required': 0, //NONE new + 'input::step': 0, //NONE new + 'input::size': 0, //NONE + 'input::src': 1, //URI + //--------------------- 'input::tabindex': 0, moved to global + 'input::type': 0, //NONE + //--------------------- 'input::usemap': 11, + 'input::value': 0, //NONE + 'input::width': 0, //NONE new + 'ins::cite': 1, //URI + 'ins::datetime': 0, //NONE + //--------------------- 'label::accesskey': 0, moved to global + 'keygen::autofocus': 0, //NONE new + 'keygen::challenge': 0, //NONE new + 'keygen::disabled': 0, //NONE new + 'keygen::form': 0, //NONE new + 'keygen::keytype': 0, //NONE new + 'keygen::name': 8, //LOCAL_NAME new + 'label::for': 5, //IDREF + 'label::form': 0, //NONE new + //--------------------- 'label::onblur': 2, + //--------------------- 'label::onfocus': 2, + //--------------------- 'legend::accesskey': 0, moved to global + //--------------------- 'legend::align': 0, + //--------------------- 'li::type': 0, + 'link::href': 1, //URI new + 'link::hreflang': 0, //NONE new + 'link::media': 0, //NONE new + 'link::rel': 0, //NONE new + 'link::sizes': 0, //NONE new + 'link::type': 0, //NONE new + 'li::value': 0, //NONE new + 'map::name': 7, //GLOBAL_NAME + //--------------------- 'menu::compact': 0, + 'menu::label': 0, //NONE new + 'menu::type': 0, //NONE new + 'meta::charset': 0, //NONE new + 'meta::content': 0, //NONE new + 'meta::http-equiv': 0, //NONE new + 'meta::name': 7, //GLOBAL_NAME new + 'meter::form': 0, //NONE new + 'meter::high': 0, //NONE new + 'meter::low': 0, //NONE new + 'meter::max': 0, //NONE new + 'meter::min': 0, //NONE new + 'meter::optimum': 0, //NONE new + 'meter::value': 0, //NONE new + 'object::data': 1, //URI new + 'object::form': 0, //NONE new + 'object::height': 0, //NONE new + 'object::name': 8, //LOCAL_NAME new + 'object::type': 0, //NONE new + 'object::usemap': 11, //URI_FRAGMENT new + 'object::width': 0, //NONE new + //--------------------- 'ol::compact': 0, + 'ol::reversed': 0, //NONE new + 'ol::start': 0, //NONE + //--------------------- 'ol::type': 0, + 'optgroup::disabled': 0, //NONE + 'optgroup::label': 0, //NONE + 'option::disabled': 0, //NONE + 'option::label': 0, //NONE + 'option::selected': 0, //NONE + 'option::value': 0, //NONE + 'output::for': 5, //IDREF new + 'output::form': 0, //NONE new + 'output::name': 8, //LOCAL_NAME new + //--------------------- 'p::align': 0, + 'param::name': 8, //LOCAL_NAME new + 'param::value': 0, //NONE new + 'progress::form': 0, //NONE new + 'progress::max': 0, //NONE new + 'progress::value': 0, //NONE new + //--------------------- 'pre::width': 0, + 'q::cite': 1, //URI + 'script::async': 0, //NONE new + 'script::charset': 0, //NONE new + 'script::defer': 0, //NONE new + 'script::src': 1, //URI new + 'script::type': 0, //NONE new + 'select::autofocus': 0, //NONE new + 'select::disabled': 0, //NONE + 'select::form': 0, //NONE new + 'select::multiple': 0, //NONE + 'select::name': 8, //LOCAL_NAME + //--------------------- 'select::onblur': 2, + //--------------------- 'select::onchange': 2, + //--------------------- 'select::onfocus': 2, + 'select::required': 0, //NONE new + 'select::size': 0, //NONE + //--------------------- 'select::tabindex': 0, moved to global + 'source::media': 0, //NONE new + 'source::src': 1, //URI new + 'source::type': 0, //NONE new + 'style::media': 0, //NONE new + 'style::scoped': 0, //NONE new + 'style::type': 0, //NONE new + //--------------------- 'table::align': 0, + //--------------------- 'table::bgcolor': 0, + 'table::border': 0, //NONE + //--------------------- 'table::cellpadding': 0, + //--------------------- 'table::cellspacing': 0, + //--------------------- 'table::frame': 0, + //--------------------- 'table::rules': 0, + //--------------------- 'table::summary': 0, + //--------------------- 'table::width': 0, + //--------------------- 'tbody::align': 0, + //--------------------- 'tbody::char': 0, + //--------------------- 'tbody::charoff': 0, + //--------------------- 'tbody::valign': 0, + //--------------------- 'td::abbr': 0, + //--------------------- 'td::align': 0, + //--------------------- 'td::axis': 0, + //--------------------- 'td::bgcolor': 0, + //--------------------- 'td::char': 0, + //--------------------- 'td::charoff': 0, + 'td::colspan': 0, //NONE + 'td::headers': 6, //IDREFS + //--------------------- 'td::height': 0, + //--------------------- 'td::nowrap': 0, + 'td::rowspan': 0, //NONE + //--------------------- 'td::scope': 0, + //--------------------- 'td::valign': 0, + //--------------------- 'td::width': 0, + //--------------------- 'textarea::accesskey': 0, moved to global + 'textarea::autofocus': 0, //NONE new + 'textarea::cols': 0, //NONE + 'textarea::disabled': 0, //NONE + 'textarea::form': 0, //NONE new + 'textarea::maxlength': 0, //NONE new + 'textarea::name': 8, //LOCAL_NAME + //--------------------- 'textarea::onblur': 2, + //--------------------- 'textarea::onchange': 2, + //--------------------- 'textarea::onfocus': 2, + //--------------------- 'textarea::onselect': 2, + 'textarea::placeholder': 0, //NONE new + 'textarea::readonly': 0, //NONE + 'textarea::required': 0, //NONE new + 'textarea::rows': 0, //NONE + 'textarea::wrap': 0, //NONE new + //--------------------- 'textarea::tabindex': 0, moved to global + //--------------------- 'tfoot::align': 0, + //--------------------- 'tfoot::char': 0, + //--------------------- 'tfoot::charoff': 0, + //--------------------- 'tfoot::valign': 0, + //--------------------- 'th::abbr': 0, + //--------------------- 'th::align': 0, + //--------------------- 'th::axis': 0, + //--------------------- 'th::bgcolor': 0, + //--------------------- 'th::char': 0, + //--------------------- 'th::charoff': 0, + 'th::colspan': 0, //NONE + 'th::headers': 6, //IDREFS + //--------------------- 'th::height': 0, + //--------------------- 'th::nowrap': 0, + 'th::rowspan': 0, //NONE + 'th::scope': 0, //NONE + //--------------------- 'th::valign': 0, + //--------------------- 'th::width': 0, + //--------------------- 'thead::align': 0, + //--------------------- 'thead::char': 0, + //--------------------- 'thead::charoff': 0, + //--------------------- 'thead::valign': 0, + 'time::datetime': 0, //NONE new + 'time::pubdate': 0, //NONE new + //--------------------- 'tr::align': 0, + //--------------------- 'tr::bgcolor': 0, + //--------------------- 'tr::char': 0, + //--------------------- 'tr::charoff': 0, + //--------------------- 'tr::valign': 0, + 'track::default': 0, //NONE new + 'track::kind': 0, //NONE new + 'track::label': 0, //NONE new + 'track::src': 1, //URI new + 'track::srclang': 0, //NONE new + //--------------------- 'ul::compact': 0, + //--------------------- 'ul::type': 0 + 'video::autoplay': 0, //NONE new + 'video::controls': 0, //NONE new + 'video::height': 0, //NONE new + 'video::loop': 0, //NONE new + 'video::mediagroup': 0, //NONE new + 'video::poster': 1, //URI new + 'video::preload': 0, //NONE new + 'video::src': 1, //URI new + 'video::width': 0 //NONE new + }; + html4.eflags = { + OPTIONAL_ENDTAG: 1, + EMPTY: 2, + CDATA: 4, + RCDATA: 8, + UNSAFE: 16, + FOLDABLE: 32, + SCRIPT: 64, + STYLE: 128 + }; + html4.ELEMENTS = { + 'a': 0, + 'abbr': 0, + //--------------------- 'acronym': 0, + 'address': 0, + //--------------------- 'applet': 16, + 'area': 2, //EMPTY + 'article': 0, //new + 'aside': 0, //new + 'audio': 0, //new + 'b': 0, + 'base': 18, //EMPTY, UNSAFE + //--------------------- 'basefont': 18, + 'bdi': 0, //new + 'bdo': 0, + //--------------------- 'big': 0, + 'blockquote': 0, + 'body': 49, //OPTIONAL_ENDTAG, UNSAFE, FOLDABLE + 'br': 2, //EMPTY + 'button': 0, + 'canvas': 0, + 'caption': 0, + //--------------------- 'center': 0, + 'cite': 0, + 'code': 0, + 'col': 2, //EMPTY + 'colgroup': 1, //OPTIONAL_ENDTAG + 'command': 2, //EMPTY new + 'datalist': 0, //new + 'dd': 1, //OPTIONAL_ENDTAG + 'del': 0, + 'details': 0, //new + 'dfn': 0, + //--------------------- 'dir': 0, + 'div': 0, + 'dl': 0, + 'dt': 1, //OPTIONAL_ENDTAG + 'em': 0, + 'embed': 18, //EMPTY, UNSAFE new + 'fieldset': 0, + 'figcaption': 0, //new + 'figure': 0, //new + //--------------------- 'font': 0, + 'footer': 0, //new + 'form': 0, + //--------------------- 'frame': 18, + //--------------------- 'frameset': 16, + 'h1': 0, + 'h2': 0, + 'h3': 0, + 'h4': 0, + 'h5': 0, + 'h6': 0, + 'head': 49, //OPTIONAL_ENDTAG, UNSAFE, FOLDABLE + 'header': 0, //new + 'hgroup': 0, //new + 'hr': 2, //EMPTY + 'html': 49, //OPTIONAL_ENDTAG, UNSAFE, FOLDABLE + 'i': 0, + 'iframe': 0, //new + 'img': 2,//EMPTY + 'input': 2, //EMPTY + 'ins': 0, + //--------------------- 'isindex': 18, + 'kbd': 0, + 'keygen': 2, //EMPTY new + 'label': 0, + 'legend': 0, + 'li': 1, //OPTIONAL_ENDTAG + 'link': 18, //EMPTY, UNSAFE + 'map': 0, + 'mark': 0, //new + 'menu': 0, + 'meta': 18, //EMPTY, UNSAFE + 'meter': 0, //new + 'nav': 0, + //--------------------- 'nobr': 0, + //--------------------- 'noembed': 4, + //--------------------- 'noframes': 20, + 'noscript': 20, //CDATA, UNSAFE + 'object': 16, //UNSAFE + 'ol': 0, + 'optgroup': 1, //OPTIONAL_ENDTAG new !!!!vorher 0 + 'option': 1, //OPTIONAL_ENDTAG + 'output': 0, //new + 'p': 1, //OPTIONAL_ENDTAG + 'param': 18, //EMPTY, UNSAFE + 'pre': 0, + 'progress': 0, //new + 'q': 0, + 'rp': 1, //OPTIONAL_ENDTAG new + 'rt': 1, //OPTIONAL_ENDTAG new + 'ruby': 0, //new + 's': 0, + 'samp': 0, + 'script': 84, //CDATA, UNSAFE, SCRIPT + 'section': 0, //new + 'select': 0, + 'small': 0, + 'source': 2, //EMPTY new + 'span': 0, + //--------------------- 'strike': 0, + 'strong': 0, + 'style': 148, //CDATA, UNSAFE, STYLE + 'sub': 0, + 'summary': 0, //new + 'sup': 0, + 'table': 0, + 'tbody': 1, //OPTIONAL_ENDTAG + 'td': 1, //OPTIONAL_ENDTAG + 'textarea': 8, //RCDATA + 'tfoot': 1, //OPTIONAL_ENDTAG + 'th': 1, //OPTIONAL_ENDTAG + 'thead': 1, //OPTIONAL_ENDTAG + 'time': 0, //new + 'title': 24, //RCDATA, UNSAFE + 'tr': 1, //OPTIONAL_ENDTAG + 'track': 2, //EMPTY new + //--------------------- 'tt': 0, + 'u': 0, + 'ul': 0, + 'var': 0, + 'video': 0, //new + 'wbr': 2 //EMPTY new + }; + html4.ueffects = { + NOT_LOADED: 0, + SAME_DOCUMENT: 1, + NEW_DOCUMENT: 2 + }; + html4.URIEFFECTS = { + 'a::href': 2, //NEW_DOCUMENT + 'area::href': 2, //NEW_DOCUMENT + 'audio::src': 1, //SAME_DOCUMENT new + 'base::href':2, //NEW_DOCUMENT new + 'blockquote::cite': 0, //NOT_LOADED + //--------------------- 'body::background': 1, + 'button::formaction': 2, //NEW_DOCUMENT new + 'command::icon': 1, //SAME_DOCUMENT new + 'del::cite': 0, //NOT_LOADED + 'embed::src': 1, //SAME_DOCUMENT new + 'form::action': 2, //NEW_DOCUMENT + 'html:: manifest': 1, //SAME_DOCUMENT new + 'iframe::src': 1, //SAME_DOCUMENT new + 'img::src': 1, //SAME_DOCUMENT + 'input::formaction': 2, //NEW_DOCUMENT new + 'input::src': 1, //SAME_DOCUMENT + 'ins::cite': 0, //NOT_LOADED + 'link::href': 2, //NEW_DOCUMENT new + 'object::data': 1, //SAME_DOCUMENT new + 'q::cite': 0, //NOT_LOADED + 'script::src': 1, //SAME_DOCUMENT new + 'source::src': 1, //SAME_DOCUMENT new + 'track::src': 1, //SAME_DOCUMENT new + 'video::poster': 1, //SAME_DOCUMENT new + 'video::src': 1 //SAME_DOCUMENT new + }; + html4.ltypes = { + UNSANDBOXED: 2, + SANDBOXED: 1, + DATA: 0 + }; + html4.LOADERTYPES = { + 'a::href': 2, //UNSANDBOXED + 'area::href': 2, //UNSANDBOXED + 'audio::src': 1, //SANDBOXED new + 'base::href': 2, //UNSANDBOXED new + 'blockquote::cite': 2, //UNSANDBOXED + //--------------------- 'body::background': 1, + 'button::formaction': 2, //UNSANDBOXED new + 'command::icon': 1, //SANDBOXED new + 'del::cite': 2, //UNSANDBOXED + 'embed::src': 1, //SANDBOXED new + 'form::action': 2, //UNSANDBOXED + 'html:: manifest': 1, //SANDBOXED new + 'iframe::src': 1, //SANDBOXED new + 'img::src': 1, //SANDBOXED + 'input::formaction': 2, //UNSANDBOXED new + 'input::src': 1, //SANDBOXED + 'ins::cite': 2, //UNSANDBOXED + 'link::href': 2, //UNSANDBOXED new + 'object::data': 0, //DATA new + 'q::cite': 2, //UNSANDBOXED + 'script::src': 1, //SANDBOXED new + 'source::src': 1, //SANDBOXED new + 'track::src': 1, //SANDBOXED new + 'video::poster': 1, //SANDBOXED new + 'video::src': 1 //SANDBOXED new + };if (typeof window !== 'undefined') { + window['html4'] = html4; + }// Copyright (C) 2006 Google Inc. + // + // 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. + + /** + * @fileoverview + * An HTML sanitizer that can satisfy a variety of security policies. + * + *

+ * The HTML sanitizer is built around a SAX parser and HTML element and + * attributes schemas. + * + * If the cssparser is loaded, inline styles are sanitized using the + * css property and value schemas. Else they are remove during + * sanitization. + * + * If it exists, uses parseCssDeclarations, sanitizeCssProperty, cssSchema + * + * @author mikesamuel@gmail.com + * @author jasvir@gmail.com + * \@requires html4 + * \@overrides window + * \@provides html, html_sanitize + */ + + /** + * \@namespace + */ + var html = (function(html4) { + + // For closure compiler + var parseCssDeclarations, sanitizeCssProperty, cssSchema; + if ('undefined' !== typeof window) { + parseCssDeclarations = window['parseCssDeclarations']; + sanitizeCssProperty = window['sanitizeCssProperty']; + cssSchema = window['cssSchema']; + } - var decimalEscapeRe = /^#(\d+)$/; - var hexEscapeRe = /^#x([0-9A-Fa-f]+)$/; + var lcase; + // The below may not be true on browsers in the Turkish locale. + if ('script' === 'SCRIPT'.toLowerCase()) { + lcase = function(s) { return s.toLowerCase(); }; + } else { /** - * Decodes an HTML entity. - * * {\@updoc - * $ lookupEntity('lt') - * # '<' - * $ lookupEntity('GT') - * # '>' - * $ lookupEntity('amp') - * # '&' - * $ lookupEntity('nbsp') - * # '\xA0' - * $ lookupEntity('apos') - * # "'" - * $ lookupEntity('quot') - * # '"' - * $ lookupEntity('#xa') - * # '\n' - * $ lookupEntity('#10') - * # '\n' - * $ lookupEntity('#x0a') - * # '\n' - * $ lookupEntity('#010') - * # '\n' - * $ lookupEntity('#x00A') - * # '\n' - * $ lookupEntity('Pi') // Known failure - * # '\u03A0' - * $ lookupEntity('pi') // Known failure - * # '\u03C0' + * $ lcase('SCRIPT') + * # 'script' + * $ lcase('script') + * # 'script' * } - * - * @param {string} name the content between the '&' and the ';'. - * @return {string} a single unicode code-point as a string. */ - function lookupEntity(name) { - name = lcase(name); // TODO: π is different from Π - if (ENTITIES.hasOwnProperty(name)) { return ENTITIES[name]; } - var m = name.match(decimalEscapeRe); - if (m) { - return String.fromCharCode(parseInt(m[1], 10)); - } else if (!!(m = name.match(hexEscapeRe))) { - return String.fromCharCode(parseInt(m[1], 16)); - } - return ''; - } + lcase = function(s) { + return s.replace( + /[A-Z]/g, + function(ch) { + return String.fromCharCode(ch.charCodeAt(0) | 32); + }); + }; + } - function decodeOneEntity(_, name) { - return lookupEntity(name); - } + // The keys of this object must be 'quoted' or JSCompiler will mangle them! + var ENTITIES = { + 'lt': '<', + 'gt': '>', + 'amp': '&', + 'nbsp': '\xA0', + 'quot': '"', + 'apos': '\'' + }; - var nulRe = /\0/g; - function stripNULs(s) { - return s.replace(nulRe, ''); - } + var decimalEscapeRe = /^#(\d+)$/; + var hexEscapeRe = /^#x([0-9A-Fa-f]+)$/; + /** + * Decodes an HTML entity. + * + * {\@updoc + * $ lookupEntity('lt') + * # '<' + * $ lookupEntity('GT') + * # '>' + * $ lookupEntity('amp') + * # '&' + * $ lookupEntity('nbsp') + * # '\xA0' + * $ lookupEntity('apos') + * # "'" + * $ lookupEntity('quot') + * # '"' + * $ lookupEntity('#xa') + * # '\n' + * $ lookupEntity('#10') + * # '\n' + * $ lookupEntity('#x0a') + * # '\n' + * $ lookupEntity('#010') + * # '\n' + * $ lookupEntity('#x00A') + * # '\n' + * $ lookupEntity('Pi') // Known failure + * # '\u03A0' + * $ lookupEntity('pi') // Known failure + * # '\u03C0' + * } + * + * @param {string} name the content between the '&' and the ';'. + * @return {string} a single unicode code-point as a string. + */ + function lookupEntity(name) { + name = lcase(name); // TODO: π is different from Π + if (ENTITIES.hasOwnProperty(name)) { return ENTITIES[name]; } + var m = name.match(decimalEscapeRe); + if (m) { + return String.fromCharCode(parseInt(m[1], 10)); + } else if (!!(m = name.match(hexEscapeRe))) { + return String.fromCharCode(parseInt(m[1], 16)); + } + return ''; + } - var entityRe = /&(#\d+|#x[0-9A-Fa-f]+|\w+);/g; - /** - * The plain text of a chunk of HTML CDATA which possibly containing. - * - * {\@updoc - * $ unescapeEntities('') - * # '' - * $ unescapeEntities('hello World!') - * # 'hello World!' - * $ unescapeEntities('1 < 2 && 4 > 3 ') - * # '1 < 2 && 4 > 3\n' - * $ unescapeEntities('<< <- unfinished entity>') - * # '<< <- unfinished entity>' - * $ unescapeEntities('/foo?bar=baz©=true') // & often unescaped in URLS - * # '/foo?bar=baz©=true' - * $ unescapeEntities('pi=ππ, Pi=Π\u03A0') // FIXME: known failure - * # 'pi=\u03C0\u03c0, Pi=\u03A0\u03A0' - * } - * - * @param {string} s a chunk of HTML CDATA. It must not start or end inside - * an HTML entity. - */ - function unescapeEntities(s) { - return s.replace(entityRe, decodeOneEntity); - } + function decodeOneEntity(_, name) { + return lookupEntity(name); + } - var ampRe = /&/g; - var looseAmpRe = /&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi; - var ltRe = /[<]/g; - var gtRe = />/g; - var quotRe = /\"/g; + var nulRe = /\0/g; + function stripNULs(s) { + return s.replace(nulRe, ''); + } - /** - * Escapes HTML special characters in attribute values. - * - * {\@updoc - * $ escapeAttrib('') - * # '' - * $ escapeAttrib('"<<&==&>>"') // Do not just escape the first occurrence. - * # '"<<&==&>>"' - * $ escapeAttrib('Hello !') - * # 'Hello <World>!' - * } - */ - function escapeAttrib(s) { - return ('' + s).replace(ampRe, '&').replace(ltRe, '<') - .replace(gtRe, '>').replace(quotRe, '"'); - } + var entityRe = /&(#\d+|#x[0-9A-Fa-f]+|\w+);/g; + /** + * The plain text of a chunk of HTML CDATA which possibly containing. + * + * {\@updoc + * $ unescapeEntities('') + * # '' + * $ unescapeEntities('hello World!') + * # 'hello World!' + * $ unescapeEntities('1 < 2 && 4 > 3 ') + * # '1 < 2 && 4 > 3\n' + * $ unescapeEntities('<< <- unfinished entity>') + * # '<< <- unfinished entity>' + * $ unescapeEntities('/foo?bar=baz©=true') // & often unescaped in URLS + * # '/foo?bar=baz©=true' + * $ unescapeEntities('pi=ππ, Pi=Π\u03A0') // FIXME: known failure + * # 'pi=\u03C0\u03c0, Pi=\u03A0\u03A0' + * } + * + * @param {string} s a chunk of HTML CDATA. It must not start or end inside + * an HTML entity. + */ + function unescapeEntities(s) { + return s.replace(entityRe, decodeOneEntity); + } - /** - * Escape entities in RCDATA that can be escaped without changing the meaning. - * {\@updoc - * $ normalizeRCData('1 < 2 && 3 > 4 && 5 < 7&8') - * # '1 < 2 && 3 > 4 && 5 < 7&8' - * } - */ - function normalizeRCData(rcdata) { - return rcdata - .replace(looseAmpRe, '&$1') - .replace(ltRe, '<') - .replace(gtRe, '>'); - } + var ampRe = /&/g; + var looseAmpRe = /&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi; + var ltRe = /[<]/g; + var gtRe = />/g; + var quotRe = /\"/g; - // TODO(mikesamuel): validate sanitizer regexs against the HTML5 grammar at - // http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html - // http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html - // http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html - // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html - - // We initially split input so that potentially meaningful characters - // like '<' and '>' are separate tokens, using a fast dumb process that - // ignores quoting. Then we walk that token stream, and when we see a - // '<' that's the start of a tag, we use ATTR_RE to extract tag - // attributes from the next token. That token will never have a '>' - // character. However, it might have an unbalanced quote character, and - // when we see that, we combine additional tokens to balance the quote. - - var ATTR_RE = new RegExp( - '^\\s*' + - '([a-z][a-z-]*)' + // 1 = Attribute name - '(?:' + ( - '\\s*(=)\\s*' + // 2 = Is there a value? - '(' + ( // 3 = Attribute value - // TODO(felix8a): maybe use backref to match quotes - '(\")[^\"]*(\"|$)' + // 4, 5 = Double-quoted string - '|' + - '(\')[^\']*(\'|$)' + // 6, 7 = Single-quoted string - '|' + - // Positive lookahead to prevent interpretation of - // as - // TODO(felix8a): might be able to drop this case - '(?=[a-z][a-z-]*\\s*=)' + - '|' + - // Unquoted value that isn't an attribute name - // (since we didn't match the positive lookahead above) - '[^\"\'\\s]*' ) + - ')' ) + - ')?', - 'i'); - - var ENTITY_RE = /^(#[0-9]+|#x[0-9a-f]+|\w+);/i; - - // false on IE<=8, true on most other browsers - var splitWillCapture = ('a,b'.split(/(,)/).length === 3); - - // bitmask for tags with special parsing, like