diff --git a/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js b/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js index f7fea1181..c0dda68dc 100644 --- a/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js +++ b/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js @@ -1,32 +1,19 @@ const path = require("path"); -const fs = require("fs"); - -const existsAndIsFile = function (file) { - return fs.existsSync(file) && fs.statSync(file).isFile(); -}; module.exports = function ({ resolveModule } = {}) { return { name: "pnpm-resolve", resolveId: function (importee, importer) { + let module = importee; if (path.isAbsolute(importee)) { // ignore absolute paths return null; } else if (importee.startsWith("./") || importee.startsWith("../")) { // resolve relative paths - const file = path.resolve(path.dirname(importer), importee); - if (existsAndIsFile(file)) { - return file; - } else if (existsAndIsFile(`${file}.js`)) { - return `${file}.js`; - } else if (existsAndIsFile(`${file}.cjs`)) { - return `${file}.cjs`; - } else if (existsAndIsFile(`${file}.mjs`)) { - return `${file}.mjs`; - } + module = path.resolve(path.dirname(importer), importee); } - // needs to be in sync with nodeResolve - const resolvedModule = resolveModule(importee); + // try to resolve the node module using the provided function + const resolvedModule = resolveModule(module); //console.log(`Resolved ${importee} to ${resolvedModule}`); return resolvedModule; }, diff --git a/packages/ui5-tooling-modules/lib/rollup-plugin-webcomponents.js b/packages/ui5-tooling-modules/lib/rollup-plugin-webcomponents.js index c61e5526a..b422efe7b 100644 --- a/packages/ui5-tooling-modules/lib/rollup-plugin-webcomponents.js +++ b/packages/ui5-tooling-modules/lib/rollup-plugin-webcomponents.js @@ -10,7 +10,7 @@ const { lt, gte } = require("semver"); // TODO: // - enabled - disabled mapping // - Externalize UI5 Web Components specific code -module.exports = function ({ log, resolveModule, framework, options } = {}) { +module.exports = function ({ log, resolveModule, getPackageJson, framework, options } = {}) { // derive the configuration from the provided options let { skip, scoping, scopeSuffix, enrichBusyIndicator } = Object.assign({ skip: false, scoping: true, enrichBusyIndicator: false }, options); @@ -50,7 +50,13 @@ module.exports = function ({ log, resolveModule, framework, options } = {}) { if (!registryEntry) { const packageJsonPath = resolveModule(`${npmPackage}/package.json`); if (packageJsonPath) { - const packageJson = require(packageJsonPath); + let packageJson; + try { + packageJson = getPackageJson(packageJsonPath); + } catch (err) { + log.error(`Failed to parse package.json of ${npmPackage}`, err); + return undefined; + } const npmPackagePath = dirname(packageJsonPath); // check if the custom elements metadata file exists (fallback to custom-elements-internal.json for @ui5/webcomponents) let metadataPath; diff --git a/packages/ui5-tooling-modules/lib/util.js b/packages/ui5-tooling-modules/lib/util.js index 567951bcb..c03340b9b 100755 --- a/packages/ui5-tooling-modules/lib/util.js +++ b/packages/ui5-tooling-modules/lib/util.js @@ -1,6 +1,6 @@ /* eslint-disable no-unused-vars */ const path = require("path"); -const { readFileSync, statSync, readdirSync, existsSync } = require("fs"); +const { readFileSync, statSync, readdirSync, existsSync, realpathSync } = require("fs"); const { readFile, stat, writeFile, mkdir } = require("fs").promises; const rollup = require("rollup"); @@ -30,6 +30,21 @@ const sanitize = require("sanitize-filename"); const { runInContext, createContext } = require("vm"); +const { minVersion } = require("semver"); + +/** + * checks if the given version is a valid semver version + * @param {string} version the version to check + * @returns {boolean} true if the version is a valid semver version + */ +function isValidVersion(version) { + try { + return minVersion(version) !== null; + } catch (e) { + return false; + } +} + /** * helper to check the existence of a resource (case-sensitive) * @param {string} file file path @@ -40,11 +55,14 @@ function existsSyncWithCase(file) { if (dir === path.dirname(dir)) { return true; } - var filenames = readdirSync(dir); - if (filenames.indexOf(path.basename(file)) === -1) { - return false; + if (existsSync(dir)) { + var filenames = readdirSync(dir); + if (filenames.indexOf(path.basename(file)) === -1) { + return false; + } + return existsSyncWithCase(dir); } - return existsSyncWithCase(dir); + return false; } /** @@ -52,8 +70,17 @@ function existsSyncWithCase(file) { * @param {string} file file path * @returns {boolean} true if the file exists */ -function existsAndIsFile(file) { - return existsSyncWithCase(file) && statSync(file).isFile(); +function existsSyncWithCaseAndIsFile(file) { + return existsSyncWithCase(file) && existsSync(file) && statSync(file).isFile(); +} + +/** + * helper to check the existence of a "file" resource + * @param {string} file file path + * @returns {boolean} true if the file exists + */ +function existsSyncAndIsFile(file) { + return existsSync(file) && statSync(file).isFile(); } /** @@ -63,57 +90,148 @@ function existsAndIsFile(file) { */ function getModulePathWithExtension(modulePath) { // check for the module path exists and to be a file - if (existsAndIsFile(modulePath)) { + if (existsSyncWithCaseAndIsFile(modulePath)) { return modulePath; - } else if (existsAndIsFile(`${modulePath}.js`)) { + } else if (existsSyncWithCaseAndIsFile(`${modulePath}.js`)) { return `${modulePath}.js`; - } else if (existsAndIsFile(`${modulePath}.cjs`)) { + } else if (existsSyncWithCaseAndIsFile(`${modulePath}.cjs`)) { return `${modulePath}.cjs`; - } else if (existsAndIsFile(`${modulePath}.mjs`)) { + } else if (existsSyncWithCaseAndIsFile(`${modulePath}.mjs`)) { return `${modulePath}.mjs`; } // reset the module path if it doesn't exist return undefined; } -const nodeModulesDirCache = {}; /** - * find the node_modules base directories in the given directory - * @param {string} dir directory to start the search - * @param {*} folders list of found node_modules base directories - * @param {*} recursive flag whether search runs recursively - * @returns {string[]} list of found node_modules base directories + * detects the "node_modules" directories relative to the current working directory + * @param {string} cwd current working directory + * @returns {string[]} list of existing node_modules directories */ -function findNodeModules(dir, folders = [], recursive) { - if (!recursive && nodeModulesDirCache[dir]) { - return nodeModulesDirCache[dir]; - } else { - //const millis = Date.now(); - const nodeModulesDir = path.join(dir, "node_modules"); - if (existsSync(nodeModulesDir)) { - folders.push(nodeModulesDir); - //console.log("found node_modules in " + nodeModulesDir); - readdirSync(nodeModulesDir, { withFileTypes: true }).forEach((nodeModule) => { - const nodeModuleName = nodeModule.name; - const nodeModuleDir = path.join(nodeModulesDir, nodeModuleName); - if (nodeModuleName.startsWith("@")) { - readdirSync(nodeModuleDir, { withFileTypes: true }).forEach((scopedNodeModule) => { - const scopedNodeModuleDir = path.join(nodeModuleDir, scopedNodeModule.name); - if (existsSync(path.join(scopedNodeModuleDir, "package.json"))) { - findNodeModules(scopedNodeModuleDir, folders, true); - } - }); - } else if (existsSync(path.join(nodeModuleDir, "package.json"))) { - findNodeModules(nodeModuleDir, folders, true); +function detectNodeModulesPaths(cwd = process.cwd()) { + const nodeModules = []; + let dir = cwd; + while (dir !== path.dirname(dir)) { + const nm = path.join(dir, "node_modules"); + if (existsSync(nm)) { + nodeModules.push(nm); + } + dir = path.dirname(dir); + } + return nodeModules; +} + +/** + * resolves the module name by testing file extensions + * @param {string} moduleName the module name + * @param {object} options options for require.resolve + * @param {string[]} options.paths paths to lookup the module + * @returns {string} the resolved module path + */ +function resolve(moduleName, options) { + let modulePath, + errors = []; + // try to resolve the module path with the default extensions + for (const ext of ["", ".js", ".cjs", ".mjs"]) { + try { + modulePath = require.resolve(`${moduleName}${ext}`, options); + if (modulePath) { + break; + } + } catch (err) { + errors.push(err); + } + } + // if an error occurred and the module path is still undefined, we throw the error + if (modulePath === undefined && errors.length > 0) { + throw errors.shift(); // throw the first error only + } + // if the module is a built-in module, we ignore it + if (modulePath === moduleName) { + modulePath = undefined; + const err = new Error(`Found built-in module "${moduleName}". Ignoring and trigger manual resolution to find custom modules!`); + err.code = "ERR_BUILTIN_MODULE"; + throw err; + } + return modulePath; +} + +// regex to extract the NPM package name from a dependency +const npmPackageScopeRegEx = /^((?:(@[^/]+)\/)?([^/]+))(?:\/(.*))?$/; + +/** + * find the dependency by its name + * @param {string} dep name of the dependency + * @param {string} cwd current working directory + * @param {string[]} depPaths list of dependency paths + * @returns {string} the module path + */ +function findDependency(dep, cwd = process.cwd(), depPaths = []) { + let modulePath; + try { + modulePath = resolve(dep, { paths: [cwd, ...depPaths] }); + } catch (err) { + // if the module is not exported, we try to resolve it manually + const [, npmPackage, , , module] = npmPackageScopeRegEx.exec(dep) || []; + if (err.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || err.code === "ERR_BUILTIN_MODULE") { + // the node_modules path of the dependency are importan as require.resolve.paths + // returns the node_modules paths relative to the location of this module + for (const resolvePath of [...detectNodeModulesPaths(cwd), ...(require.resolve.paths(npmPackage) || [])]) { + modulePath = path.join(resolvePath, npmPackage); + if (module) { + modulePath = path.join(modulePath, module); } - }); + if (!existsSyncAndIsFile(modulePath)) { + modulePath = undefined; + } else { + // resolve the symlink to the real path + // the check for symlink is not working + // therefore we always resolve the real path + modulePath = realpathSync(modulePath); + break; + } + } + } else { + // ignoring the error + //console.error(`Failed to find dependency ${dep} due to ${err.code}`, ex); + } + } + return modulePath; +} + +/** + * find the dependencies of the current project and its transitive dependencies + * (excluding devDependencies and providedDependencies) + * @param {object} options options + * @param {string} options.cwd current working directory + * @param {string[]} options.depPaths list of dependency paths + * @param {boolean} options.linkedOnly find only the linked dependencies + * @param {string[]} options.knownDeps list of known dependencies + * @returns {string[]} array of dependency root directories + */ +function findDependencies({ cwd = process.cwd(), depPaths = [], linkedOnly, knownDeps = [] } = {}) { + const pkgJson = getPackageJson(path.join(cwd, "package.json")); + let dependencies = Object.keys(pkgJson.dependencies || {}); + if (linkedOnly) { + dependencies = dependencies.filter((dep) => { + return !isValidVersion(pkgJson.dependencies[dep]); + }); + } + const depRoots = []; + for (const dep of dependencies) { + const npmPackage = npmPackageScopeRegEx.exec(dep)?.[1]; + if (knownDeps.indexOf(npmPackage) !== -1) { + continue; } - if (!recursive) { - nodeModulesDirCache[dir] = folders; - //console.verbose(`findNodeModules(${dir}) took ${Date.now() - millis}ms`); + knownDeps.push(npmPackage); + const depPath = findDependency(path.posix.join(npmPackage, "package.json"), cwd, depPaths); + let depRoot = depPath && path.dirname(depPath); + if (depRoot && depRoots.indexOf(depRoot) === -1) { + depRoots.push(depRoot); + depRoots.push(...findDependencies({ cwd: depRoot, depPaths, linkedOnly, knownDeps })); } - return folders; } + return depRoots; } /** @@ -187,15 +305,38 @@ class BundleInfo { } } +// local cache of resolved module paths +const modulesCache = {}; + // local cache of negative modules (avoid additional lookups) const modulesNegativeCache = []; -// main field processing order (for resolveModule) -const defaultExportsFields = ["browser", "import", "require", "default"]; +// local cache for package.json files +const packageJsonCache = {}; + +// local cache for dependencies list +const findDependenciesCache = {}; + +// performance metrics +const perfmetrics = { + resolveModulesTime: 0, + resolveModules: {}, +}; -// main field processing order (for nodeResolve and resolveModule) -const defaultMainFields = ["browser", "module", "main"]; +/** + * load and cache the package.json file for the given path + * @param {string} pkgJsonFile the path of the package.json file + * @returns {object} the package.json content + */ +function getPackageJson(pkgJsonFile) { + if (!packageJsonCache[pkgJsonFile]) { + const pkgJson = JSON.parse(readFileSync(pkgJsonFile, { encoding: "utf8" })); + packageJsonCache[pkgJsonFile] = pkgJson; + } + return packageJsonCache[pkgJsonFile]; +} +// the utiltiy module module.exports = function (log, projectInfo) { /** * Checks whether the file behind the given path is a module to skip for transformation or not @@ -236,109 +377,6 @@ module.exports = function (log, projectInfo) { return isUI5Module || isSystemJSModule; } - /** - * Resolves the node module - * @param {string} moduleName name of the module - * @param {string} cwd current working directory - * @param {string[]} depPaths paths of the dependencies (in addition for cwd) - * @returns {string} path of the module if found or undefined - */ - function resolveNodeModule(moduleName, cwd = process.cwd(), depPaths = []) { - let modulePath; - //let millis = Date.now(); - const resolve = function (moduleName, options) { - try { - return require.resolve(moduleName, options); - } catch (err) { - // gracefully ignore the error - //console.error(err); - } - }; - // try to resolve the module with different file extensions - for (const ext of ["", ".js", ".cjs", ".mjs"]) { - // 1.) use default lookup - modulePath = resolve(`${moduleName}${ext}`); - if (modulePath) break; - // 2.) resolve from node_modules via regular lookup (try the lookup relative to CWD) - modulePath = resolve(`${moduleName}${ext}`, { - paths: [cwd, ...depPaths], // necessary for PNPM and/or DEBUG scenario - }); - if (modulePath) break; - // 3.) resolve from node_modules via regular lookup (try the lookup relative to the module) - const nodeModulePaths = findNodeModules(cwd); - modulePath = resolve(`${moduleName}${ext}`, { - paths: [cwd, ...nodeModulePaths], // necessary for PNPM and/or DEBUG scenario - }); - if (modulePath) break; - } - //console.log(`resolveNodeModule filter took ${Date.now() - millis}ms`, moduleName); - return modulePath; - } - - // regex to extract the NPM package name from a dependency - const npmPackageScopeRegEx = /^((?:(@[^/]+)\/)?([^/]+))(?:\/(.*))?$/; - - /** - * find the dependencies of the current project and its transitive dependencies - * (excluding devDependencies and providedDependencies) - * @param {*} cwd current working directory - * @param {*} depPaths paths of the dependencies (in addition for cwd) - * @param {*} knownDeps list of known dependencies - * @returns {string[]} array of dependency root directories - */ - function findDependencies(cwd = process.cwd(), depPaths = [], knownDeps = []) { - const pkgJson = JSON.parse(readFileSync(path.join(cwd, "package.json"), { encoding: "utf8" })); - const dependencies = Object.keys(pkgJson.dependencies || {}); - const depRoots = []; - dependencies.forEach((dep) => { - const npmPackage = npmPackageScopeRegEx.exec(dep)?.[1]; - if (knownDeps.indexOf(npmPackage) !== -1) { - return depRoots; - } - knownDeps.push(npmPackage); - let depRoot; - try { - let depPath = resolveNodeModule(dep, cwd, depPaths, knownDeps); - if (depPath !== dep) { - // find the closest package.json to the resolved module - // (maybe we should break when a package.json is found even though it is not the right one) - while (!depRoot && depPath !== cwd && depPath !== "/" && path.basename(depPath) !== "node_modules") { - depPath = path.dirname(depPath); - const pkgJsonDepPath = path.join(depPath, "package.json"); - if (existsSync(pkgJsonDepPath)) { - const pkgJsonDep = JSON.parse(readFileSync(pkgJsonDepPath, { encoding: "utf8" })); - // only if the package.json name matches the dependency name - // we consider it as the root of the dependency - if (pkgJsonDep.name === dep) { - depRoot = depPath; - break; - } - } - } - } else { - // native modules are not part of the node_modules directory - // so we need to resolve it late with the package.json - depRoot = undefined; - } - } catch (ex) { - /* noop */ - } - if (!depRoot) { - try { - const depPath = resolveNodeModule(`${npmPackage}/package.json`, cwd, depPaths, knownDeps); - depRoot = path.dirname(depPath); - } catch (ex) { - /* noop */ - } - } - if (depRoot && depRoots.indexOf(depRoot) === -1) { - depRoots.push(depRoot); - depRoots.push(...findDependencies(depRoot, [...depPaths, cwd], knownDeps)); - } - }); - return depRoots; - } - const that = { /** * scans the project resources @@ -353,7 +391,7 @@ module.exports = function (log, projectInfo) { * @param {string[]} [options.depPaths] paths of the dependencies (in addition for cwd) * @returns {object} unique dependencies, resources, namespaces, chunks, ... */ - scan: async function (reader, config, { cwd, depPaths }) { + scan: async function (reader, config, { cwd = process.cwd(), depPaths = [] }) { const { parse } = await import("@typescript-eslint/typescript-estree"); const { walk } = await import("estree-walker"); @@ -571,7 +609,6 @@ module.exports = function (log, projectInfo) { } catch (err) { log.error(`Failed to parse the "${node[key]}" as JS object!`); } - return; } }); // nodes @@ -677,30 +714,38 @@ module.exports = function (log, projectInfo) { }; }, /** - * Resolves the bare module name from node_modules utilizing the require.resolve + * Resolves the bare module name from node_modules utilizing Node.js resolution algorithm * @param {string} moduleName name of the module (e.g. "chart.js/auto") * @param {object} options configuration options * @param {string} options.cwd current working directory * @param {string[]} options.depPaths paths of the dependencies (in addition for cwd) - * @param {string[]} options.mainFields an order of main fields to check in package.json - * @param {string[]} options.exportsFields an order of exports fields to check in package.json * @returns {string} the path of the module in the filesystem */ // ignore module paths starting with a segment from the ignore list (TODO: maybe a better check?) - resolveModule: function resolveModule(moduleName, { cwd, depPaths, mainFields, exportsFields } = {}) { - // default the current working directory - cwd = cwd || process.cwd(); + resolveModule: function resolveModule(moduleName, { cwd = process.cwd(), depPaths = [] } = {}) { + // create a cache key for the module and check the cache + const cacheKey = createHash("md5") + .update(`${[moduleName, cwd, ...depPaths].sort().join(",")}`) + .digest("hex"); + if (modulesCache[cacheKey]) { + return modulesCache[cacheKey]; + } // if a module is listed in the negative cache, we ignore it! if (modulesNegativeCache.indexOf(moduleName) !== -1 || /^\./.test(moduleName)) { return undefined; } - // package.json of app - const pkg = require(path.join(cwd, "package.json")); - // default the mainFields and exportsFields - mainFields = mainFields || defaultMainFields; - exportsFields = exportsFields || defaultExportsFields; // retrieve or create a resolved module - log.verbose(`Resolving ${moduleName} [${mainFields}]...`); + const millis = Date.now(); + log.verbose(`Resolving ${moduleName}...`); + // package.json of app + const pkg = getPackageJson(path.join(cwd, "package.json")); + // create the extended dependencies path (incl. direct dependencies for module lookup) + // hint: we include the direct dependencies to resolve the module path in the context + // of the app (which is required e.g. when linking dependencies to the project) + if (!findDependenciesCache[cwd]) { + findDependenciesCache[cwd] = findDependencies({ cwd, depPaths, linkedOnly: true }); + } + const extendedDepPaths = [...depPaths, ...findDependenciesCache[cwd]]; // no module found => resolve it let modulePath; // resolve the module path @@ -710,54 +755,160 @@ module.exports = function (log, projectInfo) { // check for the module path exists and to be a file modulePath = getModulePathWithExtension(modulePath); } else { - // derive the module path from the package.json entries browser, module or main - try { - const pkgJsonModuleName = path.posix.join(moduleName, "package.json"); - const pkgJson = require(pkgJsonModuleName); - const resolveModulePath = function (exports, fields) { - for (const field of fields) { - if (typeof exports[field] === "string") { - let modulePath = path.join(path.dirname(resolveNodeModule(pkgJsonModuleName, cwd, depPaths)), exports[field]); - // check for the module path exists and to be a file - modulePath = getModulePathWithExtension(modulePath); - // stop the loop if the module path is found - if (modulePath) { - return modulePath; - } + // Implementation of the Node.js Package Entry Points mechanism + // https://nodejs.org/api/packages.html#package-entry-points + let pkgJsonFile, + relativeModulePath, + isEntryModule = true; + + // 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) + if (path.isAbsolute(moduleName)) { + // lookup the parent dirs recursive to find package.json + const nodeModules = `${path.sep}node_modules${path.sep}`; + if (moduleName.lastIndexOf(nodeModules) > -1) { + const localModuleRootPath = moduleName.substring(0, moduleName.lastIndexOf(nodeModules) + nodeModules.length); + const localModuleName = moduleName.substring(localModuleRootPath.length)?.replace(/\\/g, "/"); + const [, npmPackage] = npmPackageScopeRegEx.exec(localModuleName) || []; + pkgJsonFile = path.join(localModuleRootPath, npmPackage, "package.json"); + if (!existsSyncAndIsFile(pkgJsonFile)) { + pkgJsonFile = undefined; + } + } else { + let dir = path.dirname(moduleName); + while (dir !== path.dirname(dir)) { + const pkgJson = path.join(dir, "package.json"); + if (existsSyncAndIsFile(pkgJson)) { + pkgJsonFile = pkgJson; + break; } + dir = path.dirname(dir); } - }; - // resolve the module path from exports information - // 1.) the browser field in package.json > exports > "." - if (typeof pkgJson?.exports?.["."] === "object" && typeof pkgJson?.exports?.["."].browser === "object") { - modulePath = resolveModulePath(pkgJson.exports["."].browser, exportsFields); } - // 2.) the browser field in package.json - if (!modulePath) { - modulePath = resolveModulePath(pkgJson, ["browser"]); + // the module path is the absolute path (but with file extension) + modulePath = getModulePathWithExtension(moduleName); + // if the absolute path is not a file we try to lookup the index module + if (modulePath === undefined) { + modulePath = getModulePathWithExtension(`${moduleName}${path.sep}index`); + } + } 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 + if (pkgJsonFile && relModulePath) { + const rootPath = path.dirname(pkgJsonFile); + modulePath = getModulePathWithExtension(path.join(rootPath, relModulePath)); // undefined if it doesn't exist + isEntryModule = false; + relativeModulePath = relModulePath; } - // 3.) the fields in package.json > exports > "." - if (!modulePath && typeof pkgJson?.exports?.["."] === "object") { - Object.values(pkgJson?.exports?.["."]).forEach((entry) => { - if (!modulePath && typeof entry === "object") { - modulePath = resolveModulePath([entry, exportsFields]); + } + + // if a package.json file was found we try to resolve the module path + // from the mappings in the package.json file (e.g. browser field) + if (pkgJsonFile) { + // determine the root path of the package.json file and load the package.json + 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)); + } + } else { + //console.error("#### UNKNOWN CASE ####", "exports", moduleName, JSON.stringify(pkgJson.exports)); } - }); - if (!modulePath) { - modulePath = resolveModulePath([pkgJson?.exports?.["."], exportsFields]); + } 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); + } else { + // no configuration found, we lookup the index module + modulePath = getModulePathWithExtension(path.join(rootPath, "index")); } } - // 4.) the fields in package.json - if (!modulePath) { - modulePath = resolveModulePath(pkgJson, mainFields); + + // 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; + } + //console.log("##################", "before ", modulePath); + modulePath = mappings[modulePath] || modulePath; + //console.log("##################", "after ", modulePath); + } + + // check for the module path exists and is a file + // only then the module path is valid and can be returned + if (modulePath !== undefined && !existsSyncAndIsFile(modulePath)) { + modulePath = undefined; } - } catch (err) { - // gracefully ignore the error - //console.error(err); } - // resolve from node_modules via regular lookup - if (!modulePath) { - modulePath = resolveNodeModule(moduleName, cwd, depPaths); + + // use the findDependency utility to resolve the module name + if (modulePath === undefined && !path.isAbsolute(moduleName)) { + //console.log("##################", "findDependency", moduleName); + modulePath = findDependency(moduleName, cwd, extendedDepPaths); } } if (modulePath === undefined) { @@ -770,6 +921,17 @@ module.exports = function (log, projectInfo) { } else { log.verbose(` => found at ${modulePath}`); } + if (modulePath) { + modulesCache[cacheKey] = modulePath; + } + const took = Date.now() - millis; + //console.log(`resolveModule "${moduleName}" took ${took}ms`); + perfmetrics.resolveModulesTime += took; + if (!perfmetrics.resolveModules[moduleName]) { + perfmetrics.resolveModules[moduleName] = took; + } else { + console.error(`Duplicate module resolution for "${moduleName}"!`); + } return modulePath; }, @@ -779,7 +941,6 @@ module.exports = function (log, projectInfo) { * @param {object} config configuration options * @param {string} config.cwd current working directory * @param {string[]} config.depPaths paths of the dependencies (in addition for cwd) - * @param {string[]} config.mainFields an order of main fields to check in package.json * @param {rollup.InputPluginOption[]} [config.beforePlugins] rollup plugins to be executed before * @param {rollup.InputPluginOption[]} [config.afterPlugins] rollup plugins to be executed after * @param {object} [config.pluginOptions] configuration options for the rollup plugins (e.g. webcomponents) @@ -788,7 +949,7 @@ module.exports = function (log, projectInfo) { * @param {boolean} [config.isMiddleware] flag if the getResource is called by the middleware * @returns {rollup.RollupOutput} the build output of rollup */ - createBundle: async function createBundle(moduleNames, { cwd, depPaths, mainFields, beforePlugins, afterPlugins, pluginOptions, generatedCode, inject, isMiddleware } = {}) { + createBundle: async function createBundle(moduleNames, { cwd = process.cwd(), depPaths = [], beforePlugins, afterPlugins, pluginOptions, generatedCode, inject, isMiddleware } = {}) { const { walk } = await import("estree-walker"); const bundle = await rollup.rollup({ input: moduleNames, @@ -800,8 +961,9 @@ module.exports = function (log, projectInfo) { preventAssignment: false, delimiters: ["\\b", "\\b"], values: { - "process.env.NODE_ENV": JSON.stringify(isMiddleware ? "development" : "production"), - "process.versions.node": JSON.stringify("18.15.0"), // needed for some modules to select features + "global.process.versions.node": JSON.stringify("false"), // in some cases, the global.process.versions.node is used to detect the existence of Node.js + "process.versions.node": JSON.stringify("18.15.0"), // needed for some modules to select features based on the Node.js version + "process.env.NODE_ENV": JSON.stringify("production"), // we always build in production mode }, }), injectESModule(), @@ -827,8 +989,9 @@ module.exports = function (log, projectInfo) { webcomponents({ log, resolveModule: function (moduleName) { - return that.resolveModule(moduleName, { cwd, depPaths, mainFields }); + return that.resolveModule(moduleName, { cwd, depPaths }); }, + getPackageJson, // use the cached package.json if possible framework: projectInfo?.framework, options: pluginOptions?.["webcomponents"], }), @@ -836,7 +999,7 @@ module.exports = function (log, projectInfo) { // resolve the modules from node_modules pnpmResolve({ resolveModule: function (moduleName) { - return that.resolveModule(moduleName, { cwd, depPaths, mainFields }); + return that.resolveModule(moduleName, { cwd, depPaths }); }, }), // the following plugins must be executed after the @@ -909,10 +1072,8 @@ module.exports = function (log, projectInfo) { getBundleInfo: async function getBundleInfo( moduleNames, { pluginOptions, skipCache, persistentCache, debug, chunksPath, skipTransform, keepDynamicImports, generatedCode, minify, inject } = {}, - { cwd, depPaths, isMiddleware } = {}, + { cwd = process.cwd(), depPaths = [], isMiddleware } = {}, ) { - cwd = cwd || process.cwd(); - let bundling = false; let bundleInfo = new BundleInfo(); const bundleCacheOptions = { @@ -975,7 +1136,6 @@ module.exports = function (log, projectInfo) { const options = { cwd, depPaths, - mainFields: defaultMainFields, beforePlugins: [logger({ log })], afterPlugins: [], generatedCode, @@ -991,21 +1151,11 @@ module.exports = function (log, projectInfo) { options.afterPlugins.push(require("@rollup/plugin-terser")()); } const nameOfModules = modules.map((module) => module.name); - let output; - try { - output = await that.createBundle(nameOfModules, options); - } catch (ex) { - // related to issue #726 for which the generation of jspdf fails on Windows machines - // when running the build in a standalone project with npm (without monorepo and pnpm) - /* debug && */ log.warn(`Failed to bundle "${nameOfModules}" using ES modules, falling back to CommonJS modules...`, ex.message); - debug && log.verbose(ex); // report error in verbose case! - output = await that.createBundle( - nameOfModules, - Object.assign({}, options, { - mainFields: ["browser", "main", "module"], - }), - ); - } + //const millis = Date.now(); + const output = await that.createBundle(nameOfModules, options); + //console.log(`createBundle overall duration: ${Date.now() - millis}ms`); + //console.log(`resolveModule overall duration: ${perfmetrics.resolveModulesTime}ms`); + //console.table(Object.entries(perfmetrics.resolveModules).filter(([key, value]) => value > 10).sort(([keyA, valueA], [keyB, valueB]) => valueB - valueA).map(([key, value]) => `${value}ms for ${key}`)); // parse the rollup build result output.forEach((module, i) => { @@ -1083,7 +1233,8 @@ module.exports = function (log, projectInfo) { } } catch (err) { if (bundling) { - log.error(`Couldn't bundle ${moduleNames}: ${err}`, err); + console.error(`Couldn't bundle ${moduleNames}!\n${err.message}\n${err.frame}`, err); + //log.error(`Couldn't bundle ${moduleNames}!\n${err.message}\n${err.frame}`); } bundleInfo.error = err; } @@ -1099,7 +1250,7 @@ module.exports = function (log, projectInfo) { * @param {boolean} [options.isMiddleware] flag if the getResource is called by the middleware * @returns {undefined|string} the content of the resource or undefined if not found */ - getResource: function getResource(resourceName, { cwd, depPaths, isMiddleware }) { + getResource: function getResource(resourceName, { cwd = process.cwd(), depPaths = [], isMiddleware }) { const resourcePath = that.resolveModule(`${resourceName}`, { cwd, depPaths }); if (typeof resourcePath === "string" && existsSync(resourcePath)) { let code = readFileSync(resourcePath, { @@ -1124,7 +1275,7 @@ module.exports = function (log, projectInfo) { * @param {boolean} [options.onlyFiles] true, if only files should be checked * @returns {boolean} true, if the resource exists (as a folder or file) */ - existsResource: function existsResource(resourceName, { cwd, depPaths, onlyFiles }) { + existsResource: function existsResource(resourceName, { cwd = process.cwd(), depPaths = [], onlyFiles }) { // try to lookup the resource in the node_modules first const parts = /((?:@[^/]+\/)?(?:[^/]+))(.*)/.exec(resourceName); if (parts) { @@ -1150,7 +1301,7 @@ module.exports = function (log, projectInfo) { * @param {string[]} [options.ignore] list of globs to be ignored * @returns {string[]} a list of resource paths */ - listResources: function listResources(npmPackageName, { cwd, depPaths, ignore }) { + listResources: function listResources(npmPackageName, { cwd = process.cwd(), depPaths = [], ignore }) { const npmPackageJsonPath = that.resolveModule(`${npmPackageName}/package.json`, { cwd, depPaths }); if (typeof npmPackageJsonPath === "string") { const npmPackagePath = path.resolve(npmPackageJsonPath, "../"); diff --git a/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js new file mode 100644 index 000000000..738e62953 --- /dev/null +++ b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/api.js @@ -0,0 +1,7 @@ +sap.ui.define(['ui5/ecosystem/demo/app/resources/index3'], (function (index) { 'use strict'; + + try { Object.defineProperty(index.src, "__" + "esModule", { value: true }); index.src.default = index.src; } catch (ex) {} + + return index.src; + +})); 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 new file mode 100644 index 000000000..2aad2a660 --- /dev/null +++ b/packages/ui5-tooling-modules/test/__snap__/09909941/@opentelemetry/sdk-trace-web.js @@ -0,0 +1,9313 @@ +sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index3'], (function (exports, index) { 'use strict'; + + /* + * 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 SUPPRESS_TRACING_KEY = index.src.createContextKey('OpenTelemetry SDK Context Key SUPPRESS_TRACING'); + function suppressTracing(context) { + return context.setValue(SUPPRESS_TRACING_KEY, true); + } + function isTracingSuppressed(context) { + return context.getValue(SUPPRESS_TRACING_KEY) === 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 BAGGAGE_KEY_PAIR_SEPARATOR = '='; + var BAGGAGE_PROPERTIES_SEPARATOR = ';'; + var BAGGAGE_ITEMS_SEPARATOR = ','; + // Name of the http header used to propagate the baggage + var BAGGAGE_HEADER = 'baggage'; + // Maximum number of name-value pairs allowed by w3c spec + var 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; + // Maximum total length of all name-value pairs allowed by w3c spec + var 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; + }; + function serializeKeyPairs(keyPairs) { + return keyPairs.reduce(function (hValue, current) { + var 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); + // 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) { + entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString(); + } + return entry; + }); + } + function parsePairKeyValue(entry) { + var valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR); + if (valueProps.length <= 0) + return; + var keyPairPart = valueProps.shift(); + if (!keyPairPart) + return; + var 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; + if (valueProps.length > 0) { + metadata = index.src.baggageEntryMetadataFromString(valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)); + } + return { key: key, value: value, metadata: metadata }; + } + + /* + * 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. + */ + /** + * Propagates {@link Baggage} through Context format propagation. + * + * 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); + if (!baggage || isTracingSuppressed(context)) + return; + var keyPairs = getKeyPairs(baggage) + .filter(function (pair) { + return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; + }) + .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS); + var 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) + ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR) + : headerValue; + if (!baggageString) + return context; + var baggage = {}; + if (baggageString.length === 0) { + return context; + } + var pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR); + pairs.forEach(function (entry) { + var keyPair = parsePairKeyValue(entry); + if (keyPair) { + var baggageEntry = { value: keyPair.value }; + if (keyPair.metadata) { + baggageEntry.metadata = keyPair.metadata; + } + baggage[keyPair.key] = baggageEntry; + } + }); + if (Object.entries(baggage).length === 0) { + return context; + } + return index.src.propagation.setBaggage(context, index.src.propagation.createBaggage(baggage)); + }; + W3CBaggagePropagator.prototype.fields = function () { + return [BAGGAGE_HEADER]; + }; + return W3CBaggagePropagator; + }()); + + /* + * 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 __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 = {}; + 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; + } + } + } + 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; } + } + return out; + } + function isAttributeKey(key) { + return typeof key === 'string' && key.length > 0; + } + function isAttributeValue(val) { + if (val == null) { + return true; + } + if (Array.isArray(val)) { + return isHomogeneousAttributeValueArray(val); + } + 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) { + continue; + } + 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); + } + finally { if (e_2) throw e_2.error; } + } + return true; + } + function isValidPrimitiveAttributeValue(val) { + switch (typeof val) { + case 'number': + case 'boolean': + case 'string': + return true; + } + return false; + } + + /* + * 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. + */ + /** + * Returns a function that logs an error using the provided logger, or a + * console logger if one was not provided. + */ + function loggingErrorHandler() { + return function (ex) { + index.src.diag.error(stringifyException(ex)); + }; + } + /** + * Converts an exception into a string representation + * @param {Exception} ex + */ + function stringifyException(ex) { + if (typeof ex === 'string') { + return ex; + } + else { + return JSON.stringify(flattenException(ex)); + } + } + /** + * Flattens an exception into key-value pairs by traversing the prototype chain + * and coercing values to strings. Duplicate properties will not be overwritten; + * the first insert wins. + */ + function flattenException(ex) { + var result = {}; + var current = ex; + while (current !== null) { + Object.getOwnPropertyNames(current).forEach(function (propertyName) { + if (result[propertyName]) + return; + var value = current[propertyName]; + if (value) { + result[propertyName] = String(value); + } + }); + current = Object.getPrototypeOf(current); + } + return result; + } + + /* + * 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 global error handler delegate */ + var delegateHandler = loggingErrorHandler(); + /** + * Return the global error handler + * @param {Exception} ex + */ + function globalErrorHandler(ex) { + try { + delegateHandler(ex); + } + catch (_a) { } // eslint-disable-line no-empty + } + + /* + * 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 TracesSamplerValues; + (function (TracesSamplerValues) { + TracesSamplerValues["AlwaysOff"] = "always_off"; + TracesSamplerValues["AlwaysOn"] = "always_on"; + TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off"; + TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on"; + TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; + TracesSamplerValues["TraceIdRatio"] = "traceidratio"; + })(TracesSamplerValues || (TracesSamplerValues = {})); + + var DEFAULT_LIST_SEPARATOR = ","; + var 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"]; + function isEnvVarANumber(key) { + return ENVIRONMENT_NUMBERS_KEYS.indexOf(key) > -1; + } + var ENVIRONMENT_LISTS_KEYS = ["OTEL_NO_PATCH_MODULES", "OTEL_PROPAGATORS"]; + 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 = { + OTEL_SDK_DISABLED: false, + CONTAINER_NAME: "", + ECS_CONTAINER_METADATA_URI_V4: "", + ECS_CONTAINER_METADATA_URI: "", + HOSTNAME: "", + KUBERNETES_SERVICE_HOST: "", + NAMESPACE: "", + OTEL_BSP_EXPORT_TIMEOUT: 30000, + OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512, + OTEL_BSP_MAX_QUEUE_SIZE: 2048, + OTEL_BSP_SCHEDULE_DELAY: 5000, + OTEL_BLRP_EXPORT_TIMEOUT: 30000, + OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512, + OTEL_BLRP_MAX_QUEUE_SIZE: 2048, + OTEL_BLRP_SCHEDULE_DELAY: 5000, + OTEL_EXPORTER_JAEGER_AGENT_HOST: "", + OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832, + OTEL_EXPORTER_JAEGER_ENDPOINT: "", + OTEL_EXPORTER_JAEGER_PASSWORD: "", + OTEL_EXPORTER_JAEGER_USER: "", + OTEL_EXPORTER_OTLP_ENDPOINT: "", + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "", + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: "", + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: "", + OTEL_EXPORTER_OTLP_HEADERS: "", + OTEL_EXPORTER_OTLP_TRACES_HEADERS: "", + OTEL_EXPORTER_OTLP_METRICS_HEADERS: "", + OTEL_EXPORTER_OTLP_LOGS_HEADERS: "", + OTEL_EXPORTER_OTLP_TIMEOUT: 10000, + OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000, + 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_NO_PATCH_MODULES: [], + OTEL_PROPAGATORS: ["tracecontext", "baggage"], + OTEL_RESOURCE_ATTRIBUTES: "", + OTEL_SERVICE_NAME: "", + OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT, + OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT, + OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT, + OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT, + OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT, + OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT, + OTEL_SPAN_EVENT_COUNT_LIMIT: 128, + OTEL_SPAN_LINK_COUNT_LIMIT: 128, + OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT: DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, + OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT: DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT, + OTEL_TRACES_EXPORTER: "", + OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn, + OTEL_TRACES_SAMPLER_ARG: "", + OTEL_LOGS_EXPORTER: "", + OTEL_EXPORTER_OTLP_INSECURE: "", + OTEL_EXPORTER_OTLP_TRACES_INSECURE: "", + OTEL_EXPORTER_OTLP_METRICS_INSECURE: "", + OTEL_EXPORTER_OTLP_LOGS_INSECURE: "", + OTEL_EXPORTER_OTLP_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_COMPRESSION: "", + OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: "", + OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: "", + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: "", + OTEL_EXPORTER_OTLP_CLIENT_KEY: "", + OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: "", + OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: "", + OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: "", + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: "", + OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf", + OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: "http/protobuf", + OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: "http/protobuf", + OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "http/protobuf", + OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "cumulative" + }; + function parseBoolean(key, environment, values) { + if (typeof values[key] === "undefined") { + return; + } + var 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; + } + if (typeof values[name] !== "undefined") { + var value = Number(values[name]); + if (!isNaN(value)) { + if (value < min) { + environment[name] = min; + } else if (value > max) { + environment[name] = max; + } else { + environment[name] = value; + } + } + } + } + function parseStringList(name, output, input, separator) { + if (separator === void 0) { + separator = DEFAULT_LIST_SEPARATOR; + } + var givenValue = input[name]; + if (typeof givenValue === "string") { + output[name] = givenValue.split(separator).map(function (v) { + return 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 + }; + function setLogLevelFromEnv(key, environment, values) { + var value = values[key]; + if (typeof value === "string") { + var theLevel = logLevelMap[value.toUpperCase()]; + if (theLevel != null) { + environment[key] = theLevel; + } + } + } + function parseEnvironment(values) { + var environment = {}; + for (var env in DEFAULT_ENVIRONMENT) { + var key = env; + switch (key) { + case "OTEL_LOG_LEVEL": + setLogLevelFromEnv(key, environment, values); + break; + default: + if (isEnvVarABoolean(key)) { + parseBoolean(key, environment, values); + } else if (isEnvVarANumber(key)) { + parseNumber(key, environment, values); + } else if (isEnvVarAList(key)) { + parseStringList(key, environment, values); + } else { + var value = values[key]; + if (typeof value !== "undefined" && value !== null) { + environment[key] = String(value); + } + } + } + } + return environment; + } + + 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/api 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 + var _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. + */ + /** + * Gets the environment variables + */ + function getEnv() { + var 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); + + /* + * 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 otperformance = performance; + + /* + * 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 + var VERSION$1 = '1.26.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; + + /* + * 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(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. + * + * @deprecated use ATTR_DB_USER + */ + SemanticAttributes.SEMATTRS_DB_USER = TMP_DB_USER; + /** + * 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. + * + * @deprecated use ATTR_DB_JDBC_DRIVER_CLASSNAME + */ + SemanticAttributes.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + /** + * 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". + * + * @deprecated use ATTR_DB_NAME + */ + SemanticAttributes.SEMATTRS_DB_NAME = TMP_DB_NAME; + /** + * The database statement being executed. + * + * Note: The value may be sanitized to exclude sensitive information. + * + * @deprecated use ATTR_DB_STATEMENT + */ + SemanticAttributes.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + /** + * 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. + * + * @deprecated use ATTR_DB_OPERATION + */ + 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). + * + * @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. + * + * @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. + * + * @deprecated use ATTR_DB_CASSANDRA_PAGE_SIZE + */ + SemanticAttributes.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + /** + * 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 ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL + */ + SemanticAttributes.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + /** + * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + * + * 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. + * + * @deprecated use ATTR_DB_CASSANDRA_TABLE + */ + SemanticAttributes.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + /** + * Whether or not the query is idempotent. + * + * @deprecated use ATTR_DB_CASSANDRA_IDEMPOTENCE + */ + SemanticAttributes.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + /** + * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. + * + * @deprecated use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT + */ + SemanticAttributes.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + /** + * The ID of the coordinating node for a query. + * + * @deprecated use ATTR_DB_CASSANDRA_COORDINATOR_ID + */ + SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + /** + * The data center of the coordinating node for a query. + * + * @deprecated use ATTR_DB_CASSANDRA_COORDINATOR_DC + */ + 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. + * + * @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. + * + * @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`. + * + * @deprecated use ATTR_DB_MONGODB_COLLECTION + */ + 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). + * + * 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. + * + * @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. + * + * @deprecated use ATTR_EXCEPTION_TYPE + */ + SemanticAttributes.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; + /** + * The exception message. + * + * @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. + * + * @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. + * + * @deprecated use ATTR_FAAS_TRIGGER + */ + SemanticAttributes.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + /** + * The execution ID of the current function execution. + * + * @deprecated use ATTR_FAAS_EXECUTION + */ + SemanticAttributes.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + /** + * 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 + */ + SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + /** + * 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 + */ + function timeInputToHrTime(time) { + // process.hrtime + if (isTimeInputHrTime(time)) { + return time; + } + else if (typeof time === 'number') { + // Must be a performance.now() if it's smaller than process start time. + if (time < getTimeOrigin()) { + return hrTime(time); + } + else { + // epoch milliseconds or performance.timeOrigin + return millisToHrTime(time); + } + } + else if (time instanceof Date) { + return millisToHrTime(time.getTime()); + } + else { + throw TypeError('Invalid input type'); + } + } + /** + * Returns a duration of two hrTime. + * @param startTime + * @param endTime + */ + function hrTimeDuration(startTime, endTime) { + var seconds = endTime[0] - startTime[0]; + var nanos = endTime[1] - startTime[1]; + // overflow + if (nanos < 0) { + seconds -= 1; + // negate + nanos += SECOND_TO_NANOSECONDS; + } + return [seconds, nanos]; + } + /** + * Convert hrTime to nanoseconds. + * @param time + */ + function hrTimeToNanoseconds(time) { + return time[0] * SECOND_TO_NANOSECONDS + time[1]; + } + /** + * Convert hrTime to microseconds. + * @param time + */ + function hrTimeToMicroseconds(time) { + return time[0] * 1e6 + time[1] / 1e3; + } + /** + * check if time is HrTime + * @param value + */ + function isTimeInputHrTime(value) { + return (Array.isArray(value) && + value.length === 2 && + typeof value[0] === 'number' && + typeof value[1] === 'number'); + } + /** + * check if input value is a correct types.TimeInput + * @param value + */ + function isTimeInput(value) { + return (isTimeInputHrTime(value) || + typeof value === 'number' || + value instanceof Date); + } + /** + * 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]]; + // Nanoseconds + if (out[1] >= SECOND_TO_NANOSECONDS) { + out[1] -= SECOND_TO_NANOSECONDS; + out[0] += 1; + } + return out; + } + + /* + * 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 ExportResultCode; + (function (ExportResultCode) { + ExportResultCode[ExportResultCode["SUCCESS"] = 0] = "SUCCESS"; + ExportResultCode[ExportResultCode["FAILED"] = 1] = "FAILED"; + })(ExportResultCode || (ExportResultCode = {})); + + /* + * 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 __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 () { + /** + * Construct a composite propagator from a list of propagators. + * + * @param [config] Configuration object for composite propagator + */ + function CompositePropagator(config) { + if (config === void 0) { 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); }, []))); + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same carrier key, the propagator later in the list + * will "win". + * + * @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 { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + 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 + * propagators write the same context key, the propagator later in the list + * will "win". + * + * @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) { + try { + return propagator.extract(ctx, carrier, getter); + } + catch (err) { + index.src.diag.warn("Failed to inject with " + propagator.constructor.name + ". Err: " + err.message); + } + return ctx; + }, context); + }; + CompositePropagator.prototype.fields = function () { + // return a new array so our fields cannot be modified + return this._fields.slice(); + }; + return CompositePropagator; + }()); + + /* + * 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 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 = /,|=/; + /** + * 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. + */ + var MAX_TRACE_STATE_ITEMS = 32; + var MAX_TRACE_STATE_LEN = 512; + var LIST_MEMBERS_SEPARATOR = ','; + var 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. + */ + var TraceState = /** @class */ (function () { + function TraceState(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + TraceState.prototype.set = function (key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + var 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(); + traceState._internalState.delete(key); + return traceState; + }; + TraceState.prototype.get = function (key) { + return this._internalState.get(key); + }; + TraceState.prototype.serialize = function () { + var _this = this; + return this._keys() + .reduce(function (agg, key) { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + _this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); + }; + TraceState.prototype._parse = function (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); + if (i !== -1) { + var key = listMember.slice(0, i); + var 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)); + } + }; + TraceState.prototype._keys = function () { + return Array.from(this._internalState.keys()).reverse(); + }; + TraceState.prototype._clone = function () { + var traceState = new TraceState(); + traceState._internalState = new Map(this._internalState); + return traceState; + }; + 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. + */ + 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?$"); + /** + * Parses information from the [traceparent] span tag and converts it into {@link SpanContext} + * @param traceParent - A meta property that comes from server. + * It should be dynamically generated server side to have the server's request trace Id, + * a parent span Id that was set on the server's request span, + * and the trace flags to indicate the server's sampling decision + * (01 = sampled, 00 = not sampled). + * for example: '{version}-{traceId}-{spanId}-{sampleDecision}' + * For more information see {@link https://www.w3.org/TR/trace-context/} + */ + function parseTraceParent(traceParent) { + var match = TRACE_PARENT_REGEX.exec(traceParent); + if (!match) + return null; + // According to the specification the implementation should be compatible + // with future versions. If there are more parts, we only reject it if it's using version 00 + // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent + if (match[1] === '00' && match[5]) + return null; + return { + traceId: match[2], + spanId: match[3], + traceFlags: parseInt(match[4], 16), + }; + } + /** + * Propagates {@link SpanContext} through Trace Context format propagation. + * + * 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); + if (!spanContext || + isTracingSuppressed(context) || + !index.src.isSpanContextValid(spanContext)) + return; + var traceParent = VERSION + "-" + spanContext.traceId + "-" + spanContext.spanId + "-0" + Number(spanContext.traceFlags || index.src.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); + if (!traceParentHeader) + return context; + var traceParent = Array.isArray(traceParentHeader) + ? traceParentHeader[0] + : traceParentHeader; + if (typeof traceParent !== 'string') + return context; + var spanContext = parseTraceParent(traceParent); + if (!spanContext) + return context; + spanContext.isRemote = true; + var 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) + ? traceStateHeader.join(',') + : traceStateHeader; + spanContext.traceState = new TraceState(typeof state === 'string' ? state : undefined); + } + return index.src.trace.setSpanContext(context, spanContext); + }; + W3CTraceContextPropagator.prototype.fields = function () { + return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER]; + }; + return W3CTraceContextPropagator; + }()); + + /* + * 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. + */ + index.src.createContextKey('OpenTelemetry SDK Context Key RPC_METADATA'); + var RPCType; + (function (RPCType) { + RPCType["HTTP"] = "http"; + })(RPCType || (RPCType = {})); + + /* + * 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. + */ + /* eslint-disable @typescript-eslint/no-explicit-any */ + /** + * 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; + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function (arg) { + return func(transform(arg)); + }; + } + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) !== objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && + funcToString.call(Ctor) === objectCtorString); + } + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) + ? getRawTag(value) + : objectToString(value); + } + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + var unmasked = false; + try { + value[symToStringTag] = undefined; + unmasked = true; + } + catch (e) { + // silence + } + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } + else { + delete value[symToStringTag]; + } + } + return result; + } + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(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. + */ + /* eslint-disable @typescript-eslint/no-explicit-any */ + var 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(); + while (args.length > 0) { + result = mergeTwoObjects(result, args.shift(), 0, objects); + } + return result; + } + function takeValue(value) { + if (isArray(value)) { + return value.slice(); + } + return value; + } + /** + * Merges two objects + * @param one - first object + * @param two - second object + * @param level - current deep level + * @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; + if (level > MAX_LEVEL) { + return undefined; + } + level++; + if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) { + result = takeValue(two); + } + else if (isArray(one)) { + result = one.slice(); + if (isArray(two)) { + for (var 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]; + result[key] = takeValue(two[key]); + } + } + } + else if (isObject(one)) { + if (isObject(two)) { + if (!shouldMerge(one, two)) { + 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]; + if (isPrimitive(twoValue)) { + if (typeof twoValue === 'undefined') { + delete result[key]; + } + else { + // result[key] = takeValue(twoValue); + result[key] = twoValue; + } + } + else { + var obj1 = result[key]; + var 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 }); + objects.set(obj1, arr1); + objects.set(obj2, arr2); + } + result[key] = mergeTwoObjects(result[key], twoValue, level, objects); + } + } + } + } + else { + result = two; + } + } + return result; + } + /** + * Function to check if object has been already reference + * @param obj + * @param key + * @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]; + if (info.key === key && info.obj === obj) { + return true; + } + } + return false; + } + function isArray(value) { + return Array.isArray(value); + } + function isFunction(value) { + return typeof value === 'function'; + } + function isObject(value) { + return (!isPrimitive(value) && + !isArray(value) && + !isFunction(value) && + typeof value === 'object'); + } + function isPrimitive(value) { + return (typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' || + typeof value === 'undefined' || + value instanceof Date || + value instanceof RegExp || + value === null); + } + function shouldMerge(one, two) { + if (!isPlainObject(one) || !isPlainObject(two)) { + return false; + } + 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 + * + * Licensed under the Apache License, Version 2.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 urlMatches(url, urlToMatch) { + if (typeof urlToMatch === 'string') { + return url === urlToMatch; + } + else { + return !!url.match(urlToMatch); + } + } + + /* + * 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 Deferred = /** @class */ (function () { + function Deferred() { + var _this = this; + this._promise = new Promise(function (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) { + this._resolve(val); + }; + Deferred.prototype.reject = function (err) { + this._reject(err); + }; + return Deferred; + }()); + + /* + * 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 __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) { + 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]; + } + 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); }); + } + catch (err) { + this._deferred.reject(err); + } + } + return this._deferred.promise; + }; + return BindOnceFuture; + }()); + + /* + * 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. + */ + /** + * @internal + * Shared functionality used by Exporters while exporting data, including suppression of Traces. + */ + function _export(exporter, arg) { + return new Promise(function (resolve) { + // prevent downstream exporter calls from generating spans + index.src.context.with(suppressTracing(index.src.context.active()), function () { + exporter.export(arg, function (result) { + resolve(result); + }); + }); + }); + } + + /* + * 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 internal = { + _export: _export, + }; + + /* + * 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. + */ + // Event name definitions + var ExceptionEventName = 'exception'; + + /* + * 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 __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 () { + /** + * 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 + attributes) { + if (links === void 0) { links = []; } + this.attributes = {}; + this.links = []; + this.events = []; + this._droppedAttributesCount = 0; + this._droppedEventsCount = 0; + this._droppedLinksCount = 0; + this.status = { + code: index.src.SpanStatusCode.UNSET, + }; + this.endTime = [0, 0]; + this._ended = false; + this._duration = [-1, -1]; + this.name = spanName; + this._spanContext = spanContext; + this.parentSpanId = parentSpanId; + this.kind = kind; + this.links = links; + var now = Date.now(); + this._performanceStartTime = otperformance.now(); + this._performanceOffset = + now - (this._performanceStartTime + getTimeOrigin()); + this._startTimeProvided = startTime != null; + this.startTime = this._getTime(startTime !== null && startTime !== void 0 ? startTime : now); + this.resource = parentTracer.resource; + this.instrumentationLibrary = parentTracer.instrumentationLibrary; + this._spanLimits = parentTracer.getSpanLimits(); + this._attributeValueLengthLimit = + this._spanLimits.attributeValueLengthLimit || 0; + if (attributes != null) { + this.setAttributes(attributes); + } + this._spanProcessor = parentTracer.getActiveSpanProcessor(); + this._spanProcessor.onStart(this, context); + } + Span.prototype.spanContext = function () { + return this._spanContext; + }; + Span.prototype.setAttribute = function (key, value) { + if (value == null || this._isSpanEnded()) + return this; + if (key.length === 0) { + index.src.diag.warn("Invalid attribute key: " + key); + return this; + } + if (!isAttributeValue(value)) { + index.src.diag.warn("Invalid attribute value set for key: " + key); + return this; + } + if (Object.keys(this.attributes).length >= + this._spanLimits.attributeCountLimit && + !Object.prototype.hasOwnProperty.call(this.attributes, key)) { + this._droppedAttributesCount++; + return this; + } + 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; } + } + return this; + }; + /** + * + * @param name Span Name + * @param [attributesOrStartTime] Span attributes or start time + * 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) { + if (this._isSpanEnded()) + return this; + if (this._spanLimits.eventCountLimit === 0) { + index.src.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.'); + } + this.events.shift(); + this._droppedEventsCount++; + } + if (isTimeInput(attributesOrStartTime)) { + if (!isTimeInput(timeStamp)) { + timeStamp = attributesOrStartTime; + } + attributesOrStartTime = undefined; + } + var attributes = sanitizeAttributes(attributesOrStartTime); + this.events.push({ + name: name, + attributes: attributes, + time: this._getTime(timeStamp), + droppedAttributesCount: 0, + }); + return this; + }; + Span.prototype.addLink = function (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)); + return this; + }; + Span.prototype.setStatus = function (status) { + if (this._isSpanEnded()) + return this; + this.status = status; + return this; + }; + Span.prototype.updateName = function (name) { + if (this._isSpanEnded()) + return this; + this.name = name; + return this; + }; + Span.prototype.end = function (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."); + 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); + this.endTime = this.startTime.slice(); + this._duration = [0, 0]; + } + if (this._droppedEventsCount > 0) { + index.src.diag.warn("Dropped " + this._droppedEventsCount + " events because eventCountLimit reached"); + } + this._spanProcessor.onEnd(this); + }; + Span.prototype._getTime = function (inp) { + if (typeof inp === 'number' && inp < otperformance.now()) { + // must be a performance timestamp + // apply correction and convert to hrtime + return hrTime(inp + this._performanceOffset); + } + if (typeof inp === 'number') { + return millisToHrTime(inp); + } + if (inp instanceof Date) { + return millisToHrTime(inp.getTime()); + } + if (isTimeInputHrTime(inp)) { + return inp; + } + if (this._startTimeProvided) { + // if user provided a time for the start manually + // we can't use duration to calculate event/end times + return millisToHrTime(Date.now()); + } + var msDuration = otperformance.now() - this._performanceStartTime; + return addHrTimes(this.startTime, millisToHrTime(msDuration)); + }; + Span.prototype.isRecording = function () { + return this._ended === false; + }; + Span.prototype.recordException = function (exception, time) { + var attributes = {}; + if (typeof exception === 'string') { + attributes[src.SEMATTRS_EXCEPTION_MESSAGE] = exception; + } + else if (exception) { + if (exception.code) { + attributes[src.SEMATTRS_EXCEPTION_TYPE] = exception.code.toString(); + } + else if (exception.name) { + attributes[src.SEMATTRS_EXCEPTION_TYPE] = exception.name; + } + if (exception.message) { + attributes[src.SEMATTRS_EXCEPTION_MESSAGE] = exception.message; + } + if (exception.stack) { + attributes[src.SEMATTRS_EXCEPTION_STACKTRACE] = exception.stack; + } + } + // these are minimum requirements from spec + if (attributes[src.SEMATTRS_EXCEPTION_TYPE] || + attributes[src.SEMATTRS_EXCEPTION_MESSAGE]) { + this.addEvent(ExceptionEventName, attributes, time); + } + else { + index.src.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 () { + if (this._ended) { + index.src.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) { + 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 + * + * If the given attribute value is array of strings then + * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters + * + * Otherwise return same Attribute {@code value} + * + * @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; + // 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); + return value; + } + // String + if (typeof value === 'string') { + return this._truncateToLimitUtil(value, limit); + } + // Array of strings + if (Array.isArray(value)) { + return value.map(function (val) { + return 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 + * + * Licensed under the Apache License, Version 2.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. + */ + /** + * 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. + */ + /** Sampler that samples no traces. */ + var AlwaysOffSampler = /** @class */ (function () { + function AlwaysOffSampler() { + } + AlwaysOffSampler.prototype.shouldSample = function () { + return { + decision: exports.SamplingDecision.NOT_RECORD, + }; + }; + AlwaysOffSampler.prototype.toString = function () { + return 'AlwaysOffSampler'; + }; + return AlwaysOffSampler; + }()); + + /* + * 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. + */ + /** Sampler that samples all traces. */ + var AlwaysOnSampler = /** @class */ (function () { + function AlwaysOnSampler() { + } + AlwaysOnSampler.prototype.shouldSample = function () { + return { + decision: exports.SamplingDecision.RECORD_AND_SAMPLED, + }; + }; + AlwaysOnSampler.prototype.toString = function () { + return 'AlwaysOnSampler'; + }; + return AlwaysOnSampler; + }()); + + /* + * 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. + */ + /** + * 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) { + var _a, _b, _c, _d; + this._root = config.root; + if (!this._root) { + globalErrorHandler(new Error('ParentBasedSampler must have a root sampler configured')); + this._root = new AlwaysOnSampler(); + } + this._remoteParentSampled = + (_a = config.remoteParentSampled) !== null && _a !== void 0 ? _a : new AlwaysOnSampler(); + this._remoteParentNotSampled = + (_b = config.remoteParentNotSampled) !== null && _b !== void 0 ? _b : new AlwaysOffSampler(); + this._localParentSampled = + (_c = config.localParentSampled) !== null && _c !== void 0 ? _c : new AlwaysOnSampler(); + 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)) { + return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.isRemote) { + if (parentContext.traceFlags & index.src.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) { + 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; + }()); + + /* + * 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. + */ + /** 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; } + this._ratio = _ratio; + this._ratio = this._normalize(_ratio); + this._upperBound = Math.floor(this._ratio * 0xffffffff); + } + TraceIdRatioBasedSampler.prototype.shouldSample = function (context, traceId) { + return { + decision: index.src.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) { + 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); + accumulation = (accumulation ^ part) >>> 0; + } + return accumulation; + }; + return TraceIdRatioBasedSampler; + }()); + + /* + * 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 env = getEnv(); + var FALLBACK_OTEL_TRACES_SAMPLER = TracesSamplerValues.AlwaysOn; + var DEFAULT_RATIO = 1; + /** + * Load default configuration. For fields with primitive values, any user-provided + * value will override the corresponding default value. For fields with + * non-primitive values (like `spanLimits`), the user-provided value will be + * used to extend the default value. + */ + // 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(); + return { + sampler: buildSamplerFromEnv(env), + forceFlushTimeoutMillis: 30000, + generalLimits: { + attributeValueLengthLimit: _env.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT, + attributeCountLimit: _env.OTEL_ATTRIBUTE_COUNT_LIMIT, + }, + spanLimits: { + attributeValueLengthLimit: _env.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, + attributeCountLimit: _env.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, + linkCountLimit: _env.OTEL_SPAN_LINK_COUNT_LIMIT, + eventCountLimit: _env.OTEL_SPAN_EVENT_COUNT_LIMIT, + attributePerEventCountLimit: _env.OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, + attributePerLinkCountLimit: _env.OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT, + }, + }; + } + /** + * 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(); } + switch (environment.OTEL_TRACES_SAMPLER) { + case TracesSamplerValues.AlwaysOn: + return new AlwaysOnSampler(); + case TracesSamplerValues.AlwaysOff: + return new AlwaysOffSampler(); + case TracesSamplerValues.ParentBasedAlwaysOn: + return new ParentBasedSampler({ + root: new AlwaysOnSampler(), + }); + case TracesSamplerValues.ParentBasedAlwaysOff: + return new ParentBasedSampler({ + root: new AlwaysOffSampler(), + }); + case TracesSamplerValues.TraceIdRatio: + return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment)); + case TracesSamplerValues.ParentBasedTraceIdRatio: + return new ParentBasedSampler({ + 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 + "\"."); + 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 + "."); + return DEFAULT_RATIO; + } + var 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 + "."); + 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 + "."); + return DEFAULT_RATIO; + } + return probability; + } + + /* + * 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 to merge Default configuration (as specified in './config') with + * user provided configurations. + */ + function mergeConfig(userConfig) { + var perInstanceDefaults = { + sampler: buildSamplerFromEnv(), + }; + var DEFAULT_CONFIG = loadDefaultConfig(); + var 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; + } + /** + * When general limits are provided and model specific limits are not, + * configures the model specific limits by using the values from the general ones. + * @param userConfig User provided tracer configuration + */ + 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(); + /** + * Reassign span attribute count limit to use first non null value defined by user or use default value + */ + spanLimits.attributeCountLimit = + (_f = (_e = (_d = (_b = (_a = userConfig.spanLimits) === null || _a === void 0 ? void 0 : _a.attributeCountLimit) !== null && _b !== void 0 ? _b : (_c = userConfig.generalLimits) === null || _c === void 0 ? void 0 : _c.attributeCountLimit) !== null && _d !== void 0 ? _d : parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) !== null && _e !== void 0 ? _e : parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT) !== null && _f !== void 0 ? _f : DEFAULT_ATTRIBUTE_COUNT_LIMIT; + /** + * Reassign span attribute value length limit to use first non null value defined by user or use default value + */ + 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 }); + } + + /* + * 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. + */ + /** + * 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) { + this._exporter = _exporter; + this._isExporting = false; + this._finishedSpans = []; + this._droppedSpansCount = 0; + var env = getEnv(); + this._maxExportBatchSize = + typeof (config === null || config === void 0 ? void 0 : config.maxExportBatchSize) === 'number' + ? config.maxExportBatchSize + : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE; + this._maxQueueSize = + typeof (config === null || config === void 0 ? void 0 : config.maxQueueSize) === 'number' + ? config.maxQueueSize + : env.OTEL_BSP_MAX_QUEUE_SIZE; + this._scheduledDelayMillis = + typeof (config === null || config === void 0 ? void 0 : config.scheduledDelayMillis) === 'number' + ? config.scheduledDelayMillis + : env.OTEL_BSP_SCHEDULE_DELAY; + this._exportTimeoutMillis = + typeof (config === null || config === void 0 ? void 0 : config.exportTimeoutMillis) === 'number' + ? config.exportTimeoutMillis + : 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'); + this._maxExportBatchSize = this._maxQueueSize; + } + } + BatchSpanProcessorBase.prototype.forceFlush = function () { + if (this._shutdownOnce.isCalled) { + return this._shutdownOnce.promise; + } + return this._flushAll(); + }; + // does nothing. + BatchSpanProcessorBase.prototype.onStart = function (_span, _parentContext) { }; + BatchSpanProcessorBase.prototype.onEnd = function (span) { + if (this._shutdownOnce.isCalled) { + return; + } + if ((span.spanContext().traceFlags & index.src.TraceFlags.SAMPLED) === 0) { + return; + } + this._addToBuffer(span); + }; + BatchSpanProcessorBase.prototype.shutdown = function () { + return this._shutdownOnce.call(); + }; + BatchSpanProcessorBase.prototype._shutdown = function () { + var _this = this; + return Promise.resolve() + .then(function () { + return _this.onShutdown(); + }) + .then(function () { + return _this._flushAll(); + }) + .then(function () { + return _this._exporter.shutdown(); + }); + }; + /** Add a span in the buffer. */ + BatchSpanProcessorBase.prototype._addToBuffer = function (span) { + if (this._finishedSpans.length >= this._maxQueueSize) { + // limit reached, drop span + if (this._droppedSpansCount === 0) { + index.src.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"); + 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 = []; + // 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()); + } + Promise.all(promises) + .then(function () { + resolve(); + }) + .catch(reject); + }); + }; + BatchSpanProcessorBase.prototype._flushOneBatch = function () { + var _this = this; + this._clearTimer(); + if (this._finishedSpans.length === 0) { + return Promise.resolve(); + } + return new Promise(function (resolve, reject) { + var timer = setTimeout(function () { + // don't wait anymore for export, this way the next batch can start + reject(new Error('Timeout')); + }, _this._exportTimeoutMillis); + // prevent downstream exporter calls from generating spans + index.src.context.with(suppressTracing(index.src.context.active()), function () { + // 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 = []; + } + else { + 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]; + if (span.resource.asyncAttributesPending && + span.resource.waitForAsyncAttributes) { + pendingResources !== null && pendingResources !== void 0 ? pendingResources : (pendingResources = []); + pendingResources.push(span.resource.waitForAsyncAttributes()); + } + } + // Avoid scheduling a promise to make the behavior more predictable and easier to test + if (pendingResources === null) { + doExport(); + } + else { + Promise.all(pendingResources).then(doExport, function (err) { + globalErrorHandler(err); + reject(err); + }); + } + }); + }); + }; + BatchSpanProcessorBase.prototype._maybeStartTimer = function () { + var _this = this; + 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(); + } + }) + .catch(function (e) { + _this._isExporting = false; + globalErrorHandler(e); + }); + }; + // we only wait if the queue doesn't have enough elements yet + if (this._finishedSpans.length >= this._maxExportBatchSize) { + return flush(); + } + if (this._timer !== undefined) + return; + this._timer = setTimeout(function () { return flush(); }, this._scheduledDelayMillis); + unrefTimer(this._timer); + }; + BatchSpanProcessorBase.prototype._clearTimer = function () { + if (this._timer !== undefined) { + clearTimeout(this._timer); + this._timer = undefined; + } + }; + return BatchSpanProcessorBase; + }()); + + /* + * 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$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; + if ((config === null || config === void 0 ? void 0 : config.disableAutoFlushOnDocumentHide) !== true && + typeof document !== 'undefined') { + this._visibilityChangeListener = function () { + if (document.visibilityState === 'hidden') { + void _this.forceFlush(); + } + }; + this._pageHideListener = function () { + 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 () { + if (typeof document !== 'undefined') { + if (this._visibilityChangeListener) { + document.removeEventListener('visibilitychange', this._visibilityChangeListener); + } + if (this._pageHideListener) { + document.removeEventListener('pagehide', this._pageHideListener); + } + } + }; + return BatchSpanProcessor; + }(BatchSpanProcessorBase)); + + /* + * 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 SPAN_ID_BYTES = 8; + var TRACE_ID_BYTES = 16; + var RandomIdGenerator = /** @class */ (function () { + function RandomIdGenerator() { + /** + * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex + * characters corresponding to 128 bits. + */ + this.generateTraceId = getIdGenerator(TRACE_ID_BYTES); + /** + * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex + * characters corresponding to 64 bits. + */ + this.generateSpanId = getIdGenerator(SPAN_ID_BYTES); + } + return RandomIdGenerator; + }()); + var SHARED_CHAR_CODES_ARRAY = Array(32); + function getIdGenerator(bytes) { + return function generateId() { + for (var 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) { + SHARED_CHAR_CODES_ARRAY[i] += 39; + } + } + return String.fromCharCode.apply(null, SHARED_CHAR_CODES_ARRAY.slice(0, bytes * 2)); + }; + } + + /* + * 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 class represents a basic tracer. + */ + var Tracer = /** @class */ (function () { + /** + * Constructs a new Tracer instance. + */ + function Tracer(instrumentationLibrary, config, _tracerProvider) { + this._tracerProvider = _tracerProvider; + var localConfig = mergeConfig(config); + this._sampler = localConfig.sampler; + this._generalLimits = localConfig.generalLimits; + this._spanLimits = localConfig.spanLimits; + this._idGenerator = config.idGenerator || new RandomIdGenerator(); + this.resource = _tracerProvider.resource; + this.instrumentationLibrary = instrumentationLibrary; + } + /** + * Starts a new Span or returns the default NoopSpan based on the sampling + * decision. + */ + Tracer.prototype.startSpan = function (name, options, context) { + 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); + } + var parentSpan = index.src.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); + return nonRecordingSpan; + } + var parentSpanContext = parentSpan === null || parentSpan === void 0 ? void 0 : parentSpan.spanContext(); + var spanId = this._idGenerator.generateSpanId(); + var traceId; + var traceState; + var parentSpanId; + if (!parentSpanContext || + !index.src.trace.isSpanContextValid(parentSpanContext)) { + // New root span. + traceId = this._idGenerator.generateTraceId(); + } + else { + // New child span. + traceId = parentSpanContext.traceId; + 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) { + return { + context: link.context, + attributes: sanitizeAttributes(link.attributes), + }; + }); + var attributes = sanitizeAttributes(options.attributes); + // make sampling decision + var 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); + 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); + return span; + }; + Tracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { + var opts; + var ctx; + var 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; + } + 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); + }; + /** Returns the active {@link GeneralLimits}. */ + Tracer.prototype.getGeneralLimits = function () { + return this._generalLimits; + }; + /** Returns the active {@link SpanLimits}. */ + Tracer.prototype.getSpanLimits = function () { + return this._spanLimits; + }; + Tracer.prototype.getActiveSpanProcessor = function () { + return this._tracerProvider.getActiveSpanProcessor(); + }; + return Tracer; + }()); + + /* + * 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 defaultServiceName() { + return 'unknown_service'; + } + + /* + * 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$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; + }; + /** + * A Resource describes the entity for which a signals (metrics or trace) are + * collected. + */ + var Resource = /** @class */ (function () { + function Resource( + /** + * 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; + return asyncAttributes; + }, function (err) { + index.src.diag.debug("a resource's async attributes promise rejected: %s", err); + _this.asyncAttributesPending = false; + return {}; + }); + } + /** + * Returns an empty Resource + */ + Resource.empty = function () { + return Resource.EMPTY; + }; + /** + * Returns a Resource that identifies the SDK in use. + */ + Resource.default = function () { + 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 + }); + /** + * 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*/]; + } + }); + }); + }; + /** + * Returns a new, merged {@link Resource} by merging the current Resource + * with the other Resource. In case of a collision, other Resource takes + * precedence. + * + * @param other the Resource that will be merged with this. + * @returns the newly merged Resource. + */ + Resource.prototype.merge = function (other) { + var _this = this; + 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)); + if (!this._asyncAttributesPromise && + !other._asyncAttributesPromise) { + return new Resource(mergedSyncAttributes); + } + var 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); + }); + 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 }; + } + }; + + /* + * 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 __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) { + 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; } + } + return new Promise(function (resolve) { + Promise.all(promises) + .then(function () { + resolve(); + }) + .catch(function (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; } + } + }; + 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()); + } + } + 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; } + } + return new Promise(function (resolve, reject) { + Promise.all(promises).then(function () { + resolve(); + }, reject); + }); + }; + return MultiSpanProcessor; + }()); + + /* + * 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 implementation of SpanProcessor */ + var NoopSpanProcessor = /** @class */ (function () { + function NoopSpanProcessor() { + } + NoopSpanProcessor.prototype.onStart = function (_span, _context) { }; + NoopSpanProcessor.prototype.onEnd = function (_span) { }; + NoopSpanProcessor.prototype.shutdown = function () { + return Promise.resolve(); + }; + NoopSpanProcessor.prototype.forceFlush = function () { + return Promise.resolve(); + }; + return NoopSpanProcessor; + }()); + + /* + * 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.ForceFlushState = void 0; + (function (ForceFlushState) { + ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved"; + ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout"; + ForceFlushState[ForceFlushState["error"] = 2] = "error"; + ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved"; + })(exports.ForceFlushState || (exports.ForceFlushState = {})); + /** + * This class represents a basic tracer provider which platform libraries can extend + */ + var BasicTracerProvider = /** @class */ (function () { + function BasicTracerProvider(config) { + if (config === void 0) { config = {}; } + var _a; + this._registeredSpanProcessors = []; + this._tracers = new Map(); + var 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(); + if (defaultExporter !== undefined) { + var 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) || ''); + 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)); + } + // 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) { + 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); + }); + } + this._registeredSpanProcessors.push(spanProcessor); + this.activeSpanProcessor = new MultiSpanProcessor(this._registeredSpanProcessors); + }; + BasicTracerProvider.prototype.getActiveSpanProcessor = function () { + return this.activeSpanProcessor; + }; + /** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ + BasicTracerProvider.prototype.register = function (config) { + if (config === void 0) { config = {}; } + index.src.trace.setGlobalTracerProvider(this); + if (config.propagator === undefined) { + config.propagator = this._buildPropagatorFromEnv(); + } + if (config.contextManager) { + index.src.context.setGlobalContextManager(config.contextManager); + } + if (config.propagator) { + index.src.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")); + state = exports.ForceFlushState.timeout; + }, timeout); + spanProcessor + .forceFlush() + .then(function () { + clearTimeout(timeoutInterval); + if (state !== exports.ForceFlushState.timeout) { + state = exports.ForceFlushState.resolved; + resolve(state); + } + }) + .catch(function (error) { + clearTimeout(timeoutInterval); + state = exports.ForceFlushState.error; + resolve(error); + }); + }); + }); + return new Promise(function (resolve, reject) { + Promise.all(promises) + .then(function (results) { + var errors = results.filter(function (result) { return result !== exports.ForceFlushState.resolved; }); + if (errors.length > 0) { + reject(errors); + } + else { + resolve(); + } + }) + .catch(function (error) { return reject([error]); }); + }); + }; + BasicTracerProvider.prototype.shutdown = function () { + return this.activeSpanProcessor.shutdown(); + }; + /** + * TS cannot yet infer the type of this.constructor: + * https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146 + * There is no need to override either of the getters in your child class. + * The type of the registered component maps should be the same across all + * classes in the inheritance tree. + */ + BasicTracerProvider.prototype._getPropagator = function (name) { + var _a; + return (_a = this.constructor._registeredPropagators.get(name)) === null || _a === void 0 ? void 0 : _a(); + }; + BasicTracerProvider.prototype._getSpanExporter = function (name) { + var _a; + return (_a = this.constructor._registeredExporters.get(name)) === null || _a === void 0 ? void 0 : _a(); + }; + BasicTracerProvider.prototype._buildPropagatorFromEnv = function () { + var _this = this; + // 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); + if (!propagator) { + index.src.diag.warn("Propagator \"" + name + "\" requested through environment variable is unavailable."); + } + return propagator; + }); + var validPropagators = propagators.reduce(function (list, item) { + if (item) { + list.push(item); + } + return list; + }, []); + if (validPropagators.length === 0) { + return; + } + else if (uniquePropagatorNames.length === 1) { + return validPropagators[0]; + } + else { + return new CompositePropagator({ + propagators: validPropagators, + }); + } + }; + BasicTracerProvider.prototype._buildExporterFromEnv = function () { + var exporterName = getEnv().OTEL_TRACES_EXPORTER; + if (exporterName === 'none' || exporterName === '') + return; + var exporter = this._getSpanExporter(exporterName); + if (!exporter) { + index.src.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; + }()); + + /* + * 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 __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. + * + * 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() { + } + /** + * Export spans. + * @param spans + * @param resultCallback + */ + ConsoleSpanExporter.prototype.export = function (spans, resultCallback) { + return this._sendSpans(spans, resultCallback); + }; + /** + * Shutdown the exporter. + */ + ConsoleSpanExporter.prototype.shutdown = function () { + this._sendSpans([]); + return this.forceFlush(); + }; + /** + * Exports any pending spans in exporter + */ + ConsoleSpanExporter.prototype.forceFlush = function () { + return Promise.resolve(); + }; + /** + * converts span info into more readable format + * @param span + */ + ConsoleSpanExporter.prototype._exportInfo = function (span) { + var _a; + return { + resource: { + attributes: span.resource.attributes, + }, + instrumentationScope: span.instrumentationLibrary, + traceId: span.spanContext().traceId, + parentId: span.parentSpanId, + traceState: (_a = span.spanContext().traceState) === null || _a === void 0 ? void 0 : _a.serialize(), + name: span.name, + id: span.spanContext().spanId, + kind: span.kind, + timestamp: hrTimeToMicroseconds(span.startTime), + duration: hrTimeToMicroseconds(span.duration), + attributes: span.attributes, + status: span.status, + 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; } + } + if (done) { + return done({ code: ExportResultCode.SUCCESS }); + } + }; + return ConsoleSpanExporter; + }()); + + /* + * 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 __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() { + this._finishedSpans = []; + /** + * Indicates if the exporter has been "shutdown." + * When false, exported spans will not be stored in-memory. + */ + this._stopped = false; + } + InMemorySpanExporter.prototype.export = function (spans, resultCallback) { + var _a; + 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._stopped = true; + this._finishedSpans = []; + return this.forceFlush(); + }; + /** + * Exports any pending spans in the exporter + */ + InMemorySpanExporter.prototype.forceFlush = function () { + return Promise.resolve(); + }; + InMemorySpanExporter.prototype.reset = function () { + this._finishedSpans = []; + }; + InMemorySpanExporter.prototype.getFinishedSpans = function () { + return this._finishedSpans; + }; + return InMemorySpanExporter; + }()); + + /* + * 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 __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. + * + * Only spans that are sampled are converted. + * + * 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) { + 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; + var _a, _b; + if (this._shutdownOnce.isCalled) { + return; + } + if ((span.spanContext().traceFlags & index.src.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); + }); + }; + // 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); + } + return doExport(); + }, function (err) { return globalErrorHandler(err); }); + // store the unresolved exports + if (exportPromise_1 != null) { + this._unresolvedExports.add(exportPromise_1); + } + } + else { + void doExport(); + } + }; + SimpleSpanProcessor.prototype.shutdown = function () { + return this._shutdownOnce.call(); + }; + SimpleSpanProcessor.prototype._shutdown = function () { + return this._exporter.shutdown(); + }; + return SimpleSpanProcessor; + }()); + + /* + * 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 __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() { + /** + * whether the context manager is enabled or not + */ + this._enabled = false; + /** + * Keeps the reference to current context + */ + this._currentContext = index.src.ROOT_CONTEXT; + } + /** + * + * @param context + * @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); }); + }; + Object.defineProperty(contextWrapper, 'length', { + enumerable: false, + configurable: true, + writable: false, + value: target.length, + }); + return contextWrapper; + }; + /** + * Returns the active context + */ + StackContextManager.prototype.active = function () { + 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) { + // if no specific context to propagate is given, we use the current one + if (context === undefined) { + context = this.active(); + } + if (typeof target === '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; + this._enabled = false; + return this; + }; + /** + * Enables the context manager and creates a default(root) context + */ + StackContextManager.prototype.enable = function () { + if (this._enabled) { + return this; + } + this._enabled = true; + this._currentContext = index.src.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 + * @param context + * @param fn Callback 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; + try { + return fn.call.apply(fn, __spreadArray([thisArg], __read(args), false)); + } + finally { + this._currentContext = previousContext; + } + }; + return StackContextManager; + }()); + + /* + * 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 = (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); + /** + * 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; + if (config.contextManager) { + throw ('contextManager should be defined in register method not in' + + ' constructor'); + } + 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. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ + WebTracerProvider.prototype.register = function (config) { + if (config === void 0) { config = {}; } + if (config.contextManager === undefined) { + config.contextManager = new StackContextManager(); + } + if (config.contextManager) { + config.contextManager.enable(); + } + _super.prototype.register.call(this, config); + }; + return WebTracerProvider; + }(BasicTracerProvider)); + + /* + * 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.PerformanceTimingNames = void 0; + (function (PerformanceTimingNames) { + PerformanceTimingNames["CONNECT_END"] = "connectEnd"; + PerformanceTimingNames["CONNECT_START"] = "connectStart"; + PerformanceTimingNames["DECODED_BODY_SIZE"] = "decodedBodySize"; + PerformanceTimingNames["DOM_COMPLETE"] = "domComplete"; + PerformanceTimingNames["DOM_CONTENT_LOADED_EVENT_END"] = "domContentLoadedEventEnd"; + PerformanceTimingNames["DOM_CONTENT_LOADED_EVENT_START"] = "domContentLoadedEventStart"; + PerformanceTimingNames["DOM_INTERACTIVE"] = "domInteractive"; + PerformanceTimingNames["DOMAIN_LOOKUP_END"] = "domainLookupEnd"; + PerformanceTimingNames["DOMAIN_LOOKUP_START"] = "domainLookupStart"; + PerformanceTimingNames["ENCODED_BODY_SIZE"] = "encodedBodySize"; + PerformanceTimingNames["FETCH_START"] = "fetchStart"; + PerformanceTimingNames["LOAD_EVENT_END"] = "loadEventEnd"; + PerformanceTimingNames["LOAD_EVENT_START"] = "loadEventStart"; + PerformanceTimingNames["NAVIGATION_START"] = "navigationStart"; + PerformanceTimingNames["REDIRECT_END"] = "redirectEnd"; + PerformanceTimingNames["REDIRECT_START"] = "redirectStart"; + PerformanceTimingNames["REQUEST_START"] = "requestStart"; + PerformanceTimingNames["RESPONSE_END"] = "responseEnd"; + PerformanceTimingNames["RESPONSE_START"] = "responseStart"; + PerformanceTimingNames["SECURE_CONNECTION_START"] = "secureConnectionStart"; + PerformanceTimingNames["UNLOAD_EVENT_END"] = "unloadEventEnd"; + PerformanceTimingNames["UNLOAD_EVENT_START"] = "unloadEventStart"; + })(exports.PerformanceTimingNames || (exports.PerformanceTimingNames = {})); + + var urlNormalizingAnchor; + function getUrlNormalizingAnchor() { + if (!urlNormalizingAnchor) { + urlNormalizingAnchor = document.createElement("a"); + } + return urlNormalizingAnchor; + } + function hasKey(obj, key) { + return (key in obj); + } + function addSpanNetworkEvent(span, performanceName, entries, refPerfName) { + var perfTime = undefined; + var refTime = undefined; + if (hasKey(entries, performanceName) && typeof entries[performanceName] === "number") { + perfTime = entries[performanceName]; + } + var refName = refPerfName || exports.PerformanceTimingNames.FETCH_START; + if (hasKey(entries, refName) && typeof entries[refName] === "number") { + refTime = entries[refName]; + } + if (perfTime !== undefined && refTime !== undefined && perfTime >= refTime) { + span.addEvent(performanceName, perfTime); + return span; + } + return undefined; + } + function addSpanNetworkEvents(span, resource) { + addSpanNetworkEvent(span, exports.PerformanceTimingNames.FETCH_START, resource); + addSpanNetworkEvent(span, exports.PerformanceTimingNames.DOMAIN_LOOKUP_START, resource); + addSpanNetworkEvent(span, exports.PerformanceTimingNames.DOMAIN_LOOKUP_END, resource); + addSpanNetworkEvent(span, exports.PerformanceTimingNames.CONNECT_START, resource); + if (hasKey(resource, "name") && resource["name"].startsWith("https:")) { + addSpanNetworkEvent(span, exports.PerformanceTimingNames.SECURE_CONNECTION_START, resource); + } + addSpanNetworkEvent(span, exports.PerformanceTimingNames.CONNECT_END, resource); + 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]; + if (encodedLength !== undefined) { + span.setAttribute(src.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, encodedLength); + } + var decodedLength = resource[exports.PerformanceTimingNames.DECODED_BODY_SIZE]; + if (decodedLength !== undefined && encodedLength !== decodedLength) { + span.setAttribute(src.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]; + if (valueA > valueB) { + return 1; + } else if (valueA < valueB) { + return -1; + } + return 0; + }); + } + 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); + spanUrl = parsedSpanUrl.toString(); + var filteredResources = filterResourcesForSpan(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType); + if (filteredResources.length === 0) { + return { + mainRequest: undefined + }; + } + if (filteredResources.length === 1) { + return { + mainRequest: filteredResources[0] + }; + } + var 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]; + if (fetchStart < responseEnd) { + mainRequest = corsPreFlightRequest; + corsPreFlightRequest = undefined; + } + return { + corsPreFlightRequest: corsPreFlightRequest, + mainRequest: mainRequest + }; + } else { + return { + mainRequest: filteredResources[0] + }; + } + } + 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; + if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) { + bestGap = currentGap; + mainRequest = resource; + } + } + 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])); + return resource.initiatorType.toLowerCase() === (initiatorType || "xmlhttprequest") && resource.name === spanUrl && resourceStartTime >= startTime && resourceEndTime <= endTime; + }); + if (filteredResources.length > 0) { + filteredResources = filteredResources.filter(function (resource) { + return !ignoredResources.has(resource); + }); + } + return filteredResources; + } + function parseUrl(url) { + if (typeof URL === "function") { + return new URL(url, typeof document !== "undefined" ? document.baseURI : typeof location !== "undefined" ? location.href : undefined); + } + var element = getUrlNormalizingAnchor(); + element.href = url; + return element; + } + function normalizeUrl(url) { + var urlLike = parseUrl(url); + return urlLike.href; + } + function getElementXPath(target, optimised) { + if (target.nodeType === Node.DOCUMENT_NODE) { + return "/"; + } + var targetValue = getNodeValue(target, optimised); + if (optimised && targetValue.indexOf("@id") > 0) { + return targetValue; + } + var xpath = ""; + if (target.parentNode) { + xpath += getElementXPath(target.parentNode, false); + } + xpath += targetValue; + return xpath; + } + function getNodeIndex(target) { + if (!target.parentNode) { + return 0; + } + var 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; + return allowedTypes.indexOf(element.nodeType) >= 0 && localName === target.localName; + }); + if (elements.length >= 1) { + return elements.indexOf(target) + 1; + } + return 0; + } + function getNodeValue(target, optimised) { + var nodeType = target.nodeType; + var index = getNodeIndex(target); + var nodeValue = ""; + if (nodeType === Node.ELEMENT_NODE) { + var id = target.getAttribute("id"); + if (optimised && id) { + return "//*[@id=\"" + id + "\"]"; + } + nodeValue = target.localName; + } else if (nodeType === Node.TEXT_NODE || nodeType === Node.CDATA_SECTION_NODE) { + nodeValue = "text()"; + } else if (nodeType === Node.COMMENT_NODE) { + nodeValue = "comment()"; + } else { + return ""; + } + if (nodeValue && index > 1) { + return "/" + nodeValue + "[" + index + "]"; + } + return "/" + nodeValue; + } + function shouldPropagateTraceHeaders(spanUrl, propagateTraceHeaderCorsUrls) { + var propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || []; + if (typeof propagateTraceHeaderUrls === "string" || propagateTraceHeaderUrls instanceof RegExp) { + propagateTraceHeaderUrls = [propagateTraceHeaderUrls]; + } + var parsedSpanUrl = parseUrl(spanUrl); + if (parsedSpanUrl.origin === getOrigin()) { + return true; + } else { + return propagateTraceHeaderUrls.some(function (propagateTraceHeaderUrl) { + return urlMatches(spanUrl, propagateTraceHeaderUrl); + }); + } + } + + const __esModule = true; + + exports.AlwaysOffSampler = AlwaysOffSampler; + exports.AlwaysOnSampler = AlwaysOnSampler; + exports.BasicTracerProvider = BasicTracerProvider; + exports.BatchSpanProcessor = BatchSpanProcessor; + exports.ConsoleSpanExporter = ConsoleSpanExporter; + exports.InMemorySpanExporter = InMemorySpanExporter; + exports.NoopSpanProcessor = NoopSpanProcessor; + exports.ParentBasedSampler = ParentBasedSampler; + exports.RandomIdGenerator = RandomIdGenerator; + exports.SimpleSpanProcessor = SimpleSpanProcessor; + exports.Span = Span; + exports.StackContextManager = StackContextManager; + exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler; + exports.Tracer = Tracer; + exports.WebTracerProvider = WebTracerProvider; + exports.__esModule = __esModule; + exports.addSpanNetworkEvent = addSpanNetworkEvent; + exports.addSpanNetworkEvents = addSpanNetworkEvents; + exports.getElementXPath = getElementXPath; + exports.getResource = getResource; + exports.hasKey = hasKey; + exports.normalizeUrl = normalizeUrl; + exports.parseUrl = parseUrl; + exports.shouldPropagateTraceHeaders = shouldPropagateTraceHeaders; + exports.sortResources = sortResources; + +})); diff --git a/packages/ui5-tooling-modules/test/__snap__/09909941/index3.js b/packages/ui5-tooling-modules/test/__snap__/09909941/index3.js new file mode 100644 index 000000000..fbbe0dccc --- /dev/null +++ b/packages/ui5-tooling-modules/test/__snap__/09909941/index3.js @@ -0,0 +1,2415 @@ +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__/1ba7ed2d/axios.js b/packages/ui5-tooling-modules/test/__snap__/1ba7ed2d/axios.js index 10166a058..d308eeec8 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((function () { 'use strict'; +sap.ui.define(['exports'], (function (exports) { 'use strict'; var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : @@ -226,2693 +226,2691 @@ sap.ui.define((function () { 'use strict'; uptime: uptime }; - 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; + function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; } - function toByteArray(b64) { - if (!inited) { - init(); - } - 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"); - } + // utils is a library of generic helper functions non-specific to axios - // 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 {toString: toString$1} = Object.prototype; + const {getPrototypeOf} = Object; - // base64 is 4/3 + up to two characters of the original data - arr = new Arr((len * 3) / 4 - placeHolders); + const kindOf = (cache => thing => { + const str = toString$1.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + })(Object.create(null)); - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; + const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type + }; - var L = 0; + const typeOfTest = type => thing => typeof thing === type; - 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 an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ + const {isArray: isArray$1} = Array; - 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 undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ + const isUndefined = typeOfTest('undefined'); - return arr; + /** + * 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); } - function tripletToBase64(num) { - return lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f]; - } + /** + * 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'); - 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 + /** + * 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; + } - // 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 String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ + const isString = typeOfTest('string'); - // 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 a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ + const isFunction = typeOfTest('function'); - parts.push(output); + /** + * 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'); - return parts.join(""); - } + /** + * 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'; - 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]; + /** + * 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; - i += d; + /** + * 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; + } - e = s & ((1 << -nBits) - 1); - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); + }; - 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 Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ + const isDate = kindOfTest('Date'); - 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 File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ + const isFile = kindOfTest('File'); - 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$1 = {}.toString; - - var isArray$1 = - Array.isArray || - function (arr) { - return toString$1.call(arr) == "[object Array]"; - }; - - /*! - * The buffer module from node.js, for the browser. + /** + * Determine if a value is a Blob * - * @author Feross Aboukhadijeh - * @license MIT + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false */ - /* eslint-disable no-proto */ - - var INSPECT_MAX_BYTES = 50; + const isBlob = kindOfTest('Blob'); /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) + * Determine if a value is a FileList * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. + * @param {*} val The value to test * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. + * @returns {boolean} True if value is a File, otherwise false + */ + const isFileList = kindOfTest('FileList'); + + /** + * Determine if a value is a Stream * - * Note: + * @param {*} val The value to test * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * @returns {boolean} True if value is a Stream, otherwise false + */ + const isStream = (val) => isObject(val) && isFunction(val.pipe); + + /** + * Determine if a value is a FormData * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * @param {*} thing The value to test * - * - 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. + * @returns {boolean} True if value is an FormData, otherwise false */ - Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; + 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]') + ) + ) + ) + }; - /* - * Export kMaxLength after typed array support is determined. + /** + * 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 */ - 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; - } + const isURLSearchParams = kindOfTest('URLSearchParams'); - return that; - } + const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); /** - * 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. + * Trim excess whitespace off the beginning and end of a string * - * The `Uint8Array` prototype remains unmodified. + * @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, ''); - function Buffer(arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length); - } + /** + * 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; + } - // 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); - } + let i; + let l; - Buffer.poolSize = 8192; // not used by this implementation + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; - return arr; - }; + if (isArray$1(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; - function from(that, value, encodingOrOffset, length) { - if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } + } - if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, 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; + } - if (typeof value === "string") { - return fromString(that, value, encodingOrOffset); - } + const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global$1) + })(); - return fromObject(that, value); - } + const isContextDefined = (context) => !isUndefined(context) && context !== _global; /** - * 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'); - } - } + * 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$1(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; - 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); + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; } /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding); + * 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; }; - 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; - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size); + * 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 content; }; + /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size); + 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 fromString(that, string, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } + /** + * 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 = {}; - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding'); - } + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + 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); - var actual = that.write(string, encoding); + return destObj; + }; - 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); - } + /** + * 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; + }; - 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; - } + /** + * 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; + }; - function fromArrayBuffer(that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + /** + * 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)); - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError("'offset' is out of bounds"); - } + /** + * 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]; - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError("'length' is out of bounds"); - } + const iterator = generator.call(obj); - 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); - } + let result; - 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; - } + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } + }; - function fromObject(that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + /** + * 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 (that.length === 0) { - return that; - } + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } - obj.copy(that, 0, 0, len); - return that; - } + return arr; + }; - 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); - } + /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ + const isHTMLForm = kindOfTest('HTMLFormElement'); - if (obj.type === "Buffer" && isArray$1(obj.data)) { - return fromArrayLike(that, obj.data); - } - } + const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); + }; - throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); - } + /* Creating a function that will check if an object has a property. */ + const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); - 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); - } + /** + * 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'); - Buffer.compare = function compare(a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError("Arguments must be Buffers"); - } + const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; - if (a === b) return 0; + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); - var x = a.length; - var y = b.length; + Object.defineProperties(obj, reducedDescriptors); + }; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } + /** + * Makes all methods read-only + * @param {Object} obj + */ - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; + const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } - 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; - } - }; + const value = obj[name]; - Buffer.concat = function concat(list, length) { - if (!isArray$1(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } + if (!isFunction(value)) return; - if (list.length === 0) { - return Buffer.alloc(0); - } + descriptor.enumerable = false; - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } - 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; + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); }; - 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; - } + const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; - var len = string.length; - if (len === 0) return 0; + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; - // 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; + isArray$1(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); - function slowToString(encoding, start, end) { - var loweredCase = false; + return obj; + }; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + const noop = () => {}; - // 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 ""; - } + const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; + }; - if (end === undefined || end > this.length) { - end = this.length; - } + const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; - if (end <= 0) { - return ""; - } + const DIGIT = '0123456789'; - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + }; - if (end <= start) { - return ""; - } + const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; + } - if (!encoding) encoding = "utf8"; + return str; + }; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); + /** + * 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]); + } - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); + const toJSONObject = (obj) => { + const stack = new Array(10); - case "ascii": - return asciiSlice(this, start, end); + const visit = (source, i) => { - case "latin1": - case "binary": - return latin1Slice(this, start, end); + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } - case "base64": - return base64Slice(this, start, end); + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray$1(source) ? [] : {}; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } + stack[i] = undefined; - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true; + return target; + } + } - function swap(b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } + return source; + }; - 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"); - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this; + return visit(obj, 0); }; - 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"); - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this; - }; + const isAsyncFn = kindOfTest('AsyncFunction'); - 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"); - } - 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 this; - }; + const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); - 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); - }; + // original code + // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 - 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; + const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + 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) + ); + + const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof browser$1 !== 'undefined' && browser$1.nextTick || _setImmediate); + + // ********************* + + 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 }; - 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 += " ... "; + 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; } - return ""; - }; - Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError("Argument must be a Buffer"); + 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; - 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 (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } + // 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; - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + // base64 is 4/3 + up to two characters of the original data + arr = new Arr((len * 3) / 4 - placeHolders); - if (this === target) return 0; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + var L = 0; - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(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; + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } + 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; } - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; + return arr; + } - // 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; + function tripletToBase64(num) { + return lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f]; + } - // 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; + 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(""); + } - // 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; + 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 - // Normalize val - if (typeof val === "string") { - val = Buffer.from(val, encoding); + // 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)); } - // 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); + // 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 += "="; } - throw new TypeError("val must be string, number or Buffer"); + parts.push(output); + + return parts.join(""); } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + 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]; - 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; - } - } + i += d; - function read(buf, i) { - if (indexSize === 1) { - return buf[i]; - } else { - return buf.readUInt16BE(i * indexSize); - } - } + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - 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; - } - } + 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 { - 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; - } + m = m + Math.pow(2, mLen); + e = e - eBias; } - - return -1; + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); } - 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); - }; + 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; - Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; + value = Math.abs(value); - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; } else { - length = Number(length); - if (length > remaining) { - length = remaining; + 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; } } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError("Invalid hex string"); + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - 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; - } + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + buffer[offset + i - d] |= s * 128; } - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); - } + var toString = {}.toString; - function latin1Write(buf, string, offset, length) { - return asciiWrite(buf, string, offset, length); - } + var isArray = + Array.isArray || + function (arr) { + return toString.call(arr) == "[object Array]"; + }; - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + 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; } - 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 + 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 { - throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; } - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + return that; + } - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); + /** + * 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); } - if (!encoding) encoding = "utf8"; + // 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); + } - var loweredCase = false; - for (;;) { - switch (encoding) { - case "hex": - return hexWrite(this, string, offset, length); + Buffer.poolSize = 8192; // not used by this implementation - case "utf8": - case "utf-8": - return utf8Write(this, string, offset, length); + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr; + }; - case "ascii": - return asciiWrite(this, string, offset, length); + function from(that, value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } - case "latin1": - case "binary": - return latin1Write(this, string, offset, length); + if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length); + } - case "base64": - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length); + if (typeof value === "string") { + return fromString(that, value, encodingOrOffset); + } - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string, offset, length); + return fromObject(that, value); + } - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } + /** + * 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); }; - Buffer.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0), - }; - }; + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer); + } - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf); - } else { - return fromByteArray(buf.slice(start, end)); + 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 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; + 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); + } - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding); + }; - 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; - } - } - } + 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; + } - 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); - } + /** + * 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); + }; - res.push(codePoint); - i += bytesPerSequence; + function fromString(that, string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; } - return decodeCodePointsArray(res); - } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } - // 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; + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + 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); } - // 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 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 res; + return that; } - function asciiSlice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); + function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7f); + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds"); } - return ret; - } - function latin1Slice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds"); + } - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); + 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); } - return ret; + + 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; } - function hexSlice(buf, start, end) { - var len = buf.length; + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + if (that.length === 0) { + return that; + } - var out = ""; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); + obj.copy(that, 0, 0, len); + return that; } - 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); + 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 (obj.type === "Buffer" && isArray(obj.data)) { + return fromArrayLike(that, obj.data); + } } - return res; - } - Buffer.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); + } - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; + 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); + } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; + Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError("Arguments must be Buffers"); } - if (end < start) end = start; + if (a === b) return 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]; + 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; } } - return newBuf; + if (x < y) return -1; + if (y < x) return 1; + return 0; }; - /* - * 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; + 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 val; }; - Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); + Buffer.concat = function concat(list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; + if (list.length === 0) { + return Buffer.alloc(0); } - return val; - }; - - 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); - }; + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } - Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1]; + 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; }; - Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + 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 (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + this[offset + 3] * 0x1000000; - }; + var len = string.length; + if (len === 0) return 0; - Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + // 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; - return this[offset] * 0x1000000 + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]); - }; + function slowToString(encoding, start, end) { + var loweredCase = false; - Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + // 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 ""; } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (end === undefined || end > this.length) { + end = this.length; + } - return val; - }; + if (end <= 0) { + return ""; + } - Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + if (end <= start) { + return ""; } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (!encoding) encoding = "utf8"; - return val; - }; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); - 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; - }; + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); - 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; - }; + case "ascii": + return asciiSlice(this, start, end); - 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; - }; + case "latin1": + case "binary": + return latin1Slice(this, start, end); - Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + case "base64": + return base64Slice(this, start, end); - return this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24); - }; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); - Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } - return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]; - }; + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; - Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4); + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + 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"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; }; - 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); + 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"); } - - var mul = 1; - var i = 0; - this[offset] = value & 0xff; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xff; + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } - - return offset + byteLength; + return this; }; - 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); + 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"); } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xff; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xff; + 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 offset + byteLength; + return this; }; - 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; + 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); }; - 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.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; }; - 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); + 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 offset + 2; + return ""; }; - 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.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); } - } - 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); + if (start === undefined) { + start = 0; } - 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); + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; } - 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); + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); } - 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; + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; } - return offset + byteLength; - }; + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + if (this === target) return 0; - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - 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; + 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; } - this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; } - return offset + byteLength; + if (x < y) return -1; + if (y < x) return 1; + return 0; }; - 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; - }; + // 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.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); + // 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; } - 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); + // 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; } - 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); + // Normalize val + if (typeof val === "string") { + val = Buffer.from(val, encoding); } - 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); + // 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 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"); + throw new TypeError("val must be string, number or Buffer"); } - function writeFloat(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); + 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; + } } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; + + 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.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; }; - Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; - function writeDouble(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); + 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; + } } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; + + // 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; } - Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } - Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } - // 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 latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); + } - // Copy 0 bytes; we're done - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); + 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"); } - 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 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"); } - var len = end - start; - var i; + if (!encoding) encoding = "utf8"; - 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); - } + var loweredCase = false; + for (;;) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); - return len; - }; + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); - // 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); + 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; } - } 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"); - } + Buffer.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0), + }; + }; - if (end <= start) { - return this; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf); + } else { + return fromByteArray(buf.slice(start, end)); } + } - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - if (!val) val = 0; + 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; - var i; - if (typeof val === "number") { - for (i = start; i < end; ++i) { - this[i] = val; + 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; + } + } + } } - } 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]; + + 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 this; - }; + return decodeCodePointsArray(res); + } - // HELPER FUNCTIONS - // ================ + // 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; - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } - 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 + "="; + // 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 str; + return res; } - function stringtrim(str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ""); - } + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); - function toHex(n) { - if (n < 16) return "0" + n.toString(16); - return n.toString(16); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f); + } + return ret; } - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } - // 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; - } + function hexSlice(buf, start, end) { + var len = buf.length; - // valid lead - leadSurrogate = codePoint; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - continue; - } + var out = ""; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out; + } - // 2 leads in a row - if (codePoint < 0xdc00) { - if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); - leadSurrogate = codePoint; - continue; - } + 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; + } - // 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.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - leadSurrogate = null; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } - // 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"); - } + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; } - return bytes; - } + if (end < start) end = start; - 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); + 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 byteArray; + + 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"); } - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; + Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } - return byteArray; - } + return val; + }; - function base64ToBytes(str) { - return toByteArray(base64clean(str)); - } + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } - 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]; + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - return i; - } - function isnan(val) { - return val !== val; // eslint-disable-line no-self-compare - } + return val; + }; - // 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.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; - function isFastBuffer(obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); - } + Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8); + }; - // 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.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1]; + }; - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; - } + return (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + this[offset + 3] * 0x1000000; + }; - // utils is a library of generic helper functions non-specific to axios + Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - const {toString} = Object.prototype; - const {getPrototypeOf} = Object; + return this[offset] * 0x1000000 + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]); + }; - const kindOf = (cache => thing => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - })(Object.create(null)); + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - const kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type - }; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - const typeOfTest = type => thing => typeof thing === type; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - /** - * 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; + return val; + }; - /** - * 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'); + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - /** - * 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); - } + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; - /** - * 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'); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; - /** - * 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; - } + 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; + }; - /** - * 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'; + 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; + }; - /** - * 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; + 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; + }; - /** - * 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; - } + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); + return this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24); }; - /** - * 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'); + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - /** - * 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'); + return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]; + }; - /** - * 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'); + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4); + }; - /** - * 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'); + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4); + }; - /** - * 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); + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8); + }; - /** - * 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.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8); }; - /** - * 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 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"); + } - const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + 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); + } - /** - * 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, ''); + var mul = 1; + var i = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } - /** - * 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 + byteLength; + }; - let i; - let l; + 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); + } - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 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 { - // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; + return offset + byteLength; + }; - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); - } - } + 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); + } } - 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; - } - - const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : commonjsGlobal) - })(); - - const isContextDefined = (context) => !isUndefined(context) && context !== _global; + 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; + }; - /** - * 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; - } - }; + 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; + }; - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); - } - return result; + 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; + } } - /** - * 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; - }; - - /** - * 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 content; + 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; }; - /** - * 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); + 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; }; - /** - * 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 = {}; - - destObj = destObj || {}; - // eslint-disable-next-line no-eq-null,eqeqeq - if (sourceObj == null) return destObj; + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - 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); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - return destObj; - }; + 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; + } - /** - * 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; + 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); - /** - * 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; - }; - - /** - * 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)); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - /** - * 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]; + 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; + } - const iterator = generator.call(obj); + return offset + byteLength; + }; - let result; + 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; + }; - while ((result = iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[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; }; - /** - * 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 = []; + 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; + }; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } + 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; + }; - return arr; + 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; }; - /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ - const isHTMLForm = kindOfTest('HTMLFormElement'); + 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; + } - const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; - } - ); + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); }; - /* Creating a function that will check if an object has a property. */ - const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); - - /** - * 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'); + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; - const reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; - } - }); + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; - Object.defineProperties(obj, reducedDescriptors); + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); }; - /** - * Makes all methods read-only - * @param {Object} obj - */ + // 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; - const freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; - } + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; - const value = obj[name]; + // 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"); - if (!isFunction(value)) return; + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - descriptor.enumerable = false; + var len = end - start; + var i; - if ('writable' in descriptor) { - descriptor.writable = false; - return; - } + 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 (!descriptor.set) { - descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); - }; - } - }); + return len; }; - const toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; + // 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; + } - const define = (arr) => { - arr.forEach(value => { - obj[value] = true; - }); - }; + // 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"); + } - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + if (end <= start) { + return this; + } - return obj; - }; + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - const noop = () => {}; + if (!val) val = 0; - const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; - }; + 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]; + } + } - const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + return this; + }; - const DIGIT = '0123456789'; + // HELPER FUNCTIONS + // ================ - const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT - }; + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - while (size--) { - str += alphabet[Math.random() * length|0]; - } + 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 str; - }; + function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ""); + } - /** - * 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 toHex(n) { + if (n < 16) return "0" + n.toString(16); + return n.toString(16); } - const toJSONObject = (obj) => { - const stack = new Array(10); + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - const visit = (source, i) => { + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } + // 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; + } - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; + // 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; + } - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); + // 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); + } - stack[i] = undefined; + leadSurrogate = null; - return target; - } - } + // 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 source; - }; + return bytes; + } - return visit(obj, 0); - }; + 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; + } - const isAsyncFn = kindOfTest('AsyncFunction'); + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; - const isThenable = (thing) => - thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - // original code - // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + return byteArray; + } - const _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; - } + function base64ToBytes(str) { + return toByteArray(base64clean(str)); + } - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({source, data}) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); + 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; + } - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); - } - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); - })( - typeof setImmediate === 'function', - isFunction(_global.postMessage) - ); + function isnan(val) { + return val !== val; // eslint-disable-line no-self-compare + } - const asap = typeof queueMicrotask !== 'undefined' ? - queueMicrotask.bind(_global) : ( typeof browser$1 !== 'undefined' && browser$1.nextTick || _setImmediate); + // 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)); + } - // ********************* + function isFastBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); + } - 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 - }; + // 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)); + } /** * Create an Error with the specified message, config, error code, request and response. @@ -2925,7 +2923,7 @@ sap.ui.define((function () { 'use strict'; * * @returns {Error} The created error. */ - function AxiosError(message, code, config, request, response) { + function AxiosError$1(message, code, config, request, response) { Error.call(this); if (Error.captureStackTrace) { @@ -2945,7 +2943,7 @@ sap.ui.define((function () { 'use strict'; } } - utils$1.inherits(AxiosError, Error, { + utils$1.inherits(AxiosError$1, Error, { toJSON: function toJSON() { return { // Standard @@ -2967,7 +2965,7 @@ sap.ui.define((function () { 'use strict'; } }); - const prototype$1 = AxiosError.prototype; + const prototype$1 = AxiosError$1.prototype; const descriptors = {}; [ @@ -2988,11 +2986,11 @@ sap.ui.define((function () { 'use strict'; descriptors[code] = {value: code}; }); - Object.defineProperties(AxiosError, descriptors); + Object.defineProperties(AxiosError$1, descriptors); Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); // eslint-disable-next-line func-names - AxiosError.from = (error, code, config, request, response, customProps) => { + AxiosError$1.from = (error, code, config, request, response, customProps) => { const axiosError = Object.create(prototype$1); utils$1.toFlatObject(error, axiosError, function filter(obj) { @@ -3001,7 +2999,7 @@ sap.ui.define((function () { 'use strict'; return prop !== 'isAxiosError'; }); - AxiosError.call(axiosError, error.message, code, config, request, response); + AxiosError$1.call(axiosError, error.message, code, config, request, response); axiosError.cause = error; @@ -3015,214 +3013,103 @@ sap.ui.define((function () { '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); }); - - /** - * 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) { + function toFormData$1(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('Blob is not supported. Use a Buffer instead.'); + throw new AxiosError$1("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, '{}')) { - // eslint-disable-next-line no-param-reassign + if (value && !path && typeof value === "object") { + if (utils$1.endsWith(key, "{}")) { 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)) - )) { - // eslint-disable-next-line no-param-reassign + } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { key = removeBrackets(key); - arr.forEach(function each(el, index) { - !(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) - ); + !(utils$1.isUndefined(el) || el === null) && formData.append(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; } @@ -3260,7 +3147,7 @@ sap.ui.define((function () { 'use strict'; function AxiosURLSearchParams(params, options) { this._pairs = []; - params && toFormData(params, this, options); + params && toFormData$1(params, this, options); } const prototype = AxiosURLSearchParams.prototype; @@ -3404,8 +3291,6 @@ sap.ui.define((function () { 'use strict'; } } - var InterceptorManager$1 = InterceptorManager; - var transitionalDefaults = { silentJSONParsing: true, forcedJSONParsing: true, @@ -3475,8 +3360,8 @@ sap.ui.define((function () { 'use strict'; var utils = /*#__PURE__*/Object.freeze({ __proto__: null, hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, hasStandardBrowserEnv: hasStandardBrowserEnv, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, navigator: _navigator, origin: origin }); @@ -3487,7 +3372,7 @@ sap.ui.define((function () { 'use strict'; }; function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + return toFormData$1(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')); @@ -3662,7 +3547,7 @@ sap.ui.define((function () { 'use strict'; if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { const _FormData = this.env && this.env.FormData; - return toFormData( + return toFormData$1( isFileList ? {'files[]': data} : data, _FormData && new _FormData(), this.formSerializer @@ -3696,7 +3581,7 @@ sap.ui.define((function () { 'use strict'; } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } @@ -3739,8 +3624,6 @@ sap.ui.define((function () { '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([ @@ -3861,7 +3744,7 @@ sap.ui.define((function () { 'use strict'; }); } - class AxiosHeaders { + let AxiosHeaders$1 = class AxiosHeaders { constructor(headers) { headers && this.set(headers); } @@ -4072,12 +3955,12 @@ sap.ui.define((function () { 'use strict'; return this; } - } + }; - AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); // reserved names hotfix - utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => { let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` return { get: () => value, @@ -4087,9 +3970,7 @@ sap.ui.define((function () { 'use strict'; } }); - utils$1.freezeMethods(AxiosHeaders); - - var AxiosHeaders$1 = AxiosHeaders; + utils$1.freezeMethods(AxiosHeaders$1); /** * Transform the data for a request or a response @@ -4100,7 +3981,7 @@ sap.ui.define((function () { 'use strict'; * @returns {*} The resulting transformed data */ function transformData(fns, response) { - const config = this || defaults$1; + const config = this || defaults; const context = response || config; const headers = AxiosHeaders$1.from(context.headers); let data = context.data; @@ -4114,7 +3995,7 @@ sap.ui.define((function () { 'use strict'; return data; } - function isCancel(value) { + function isCancel$1(value) { return !!(value && value.__CANCEL__); } @@ -4127,13 +4008,13 @@ sap.ui.define((function () { 'use strict'; * * @returns {CanceledError} The created error. */ - function CanceledError(message, config, request) { + function CanceledError$1(message, config, request) { // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request); this.name = 'CanceledError'; } - utils$1.inherits(CanceledError, AxiosError, { + utils$1.inherits(CanceledError$1, AxiosError$1, { __CANCEL__: true }); @@ -4151,9 +4032,9 @@ sap.ui.define((function () { 'use strict'; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { - reject(new AxiosError( + reject(new AxiosError$1( 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response @@ -4460,7 +4341,7 @@ sap.ui.define((function () { 'use strict'; * * @returns {Object} New object resulting from merging config2 to config1 */ - function mergeConfig(config1, config2) { + function mergeConfig$1(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; const config = {}; @@ -4552,7 +4433,7 @@ sap.ui.define((function () { 'use strict'; } var resolveConfig = (config) => { - const newConfig = mergeConfig({}, config); + const newConfig = mergeConfig$1({}, config); let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; @@ -4687,7 +4568,7 @@ sap.ui.define((function () { 'use strict'; return; } - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request)); // Clean up request request = null; @@ -4697,7 +4578,7 @@ sap.ui.define((function () { '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('Network Error', AxiosError.ERR_NETWORK, config, request)); + reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request)); // Clean up request request = null; @@ -4710,9 +4591,9 @@ sap.ui.define((function () { 'use strict'; if (_config.timeoutErrorMessage) { timeoutErrorMessage = _config.timeoutErrorMessage; } - reject(new AxiosError( + reject(new AxiosError$1( timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, config, request)); @@ -4762,7 +4643,7 @@ sap.ui.define((function () { 'use strict'; if (!request) { return; } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel); request.abort(); request = null; }; @@ -4776,7 +4657,7 @@ sap.ui.define((function () { 'use strict'; const protocol = parseProtocol(_config.url); if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config)); return; } @@ -4799,13 +4680,13 @@ sap.ui.define((function () { 'use strict'; aborted = true; unsubscribe(); const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err)); } }; let timer = timeout && setTimeout(() => { timer = null; - onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); + onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT)); }, timeout); const unsubscribe = () => { @@ -4829,8 +4710,6 @@ sap.ui.define((function () { 'use strict'; } }; - var composeSignals$1 = composeSignals; - const streamChunk = function* (chunk, chunkSize) { let len = chunk.byteLength; @@ -4964,7 +4843,7 @@ sap.ui.define((function () { '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(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); + throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config); }); }); })(new Response)); @@ -5023,7 +4902,7 @@ sap.ui.define((function () { 'use strict'; responseType = responseType ? (responseType + '').toLowerCase() : 'text'; - let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); let request; @@ -5125,14 +5004,14 @@ sap.ui.define((function () { 'use strict'; if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { throw Object.assign( - new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), + new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request), { cause: err.cause || err } ) } - throw AxiosError.from(err, err && err.code, config, request); + throw AxiosError$1.from(err, err && err.code, config, request); } }); @@ -5177,7 +5056,7 @@ sap.ui.define((function () { 'use strict'; adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; if (adapter === undefined) { - throw new AxiosError(`Unknown adapter '${id}'`); + throw new AxiosError$1(`Unknown adapter '${id}'`); } } @@ -5199,7 +5078,7 @@ sap.ui.define((function () { 'use strict'; (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : 'as no adapter specified'; - throw new AxiosError( + throw new AxiosError$1( `There is no suitable adapter to dispatch the request ` + s, 'ERR_NOT_SUPPORT' ); @@ -5223,7 +5102,7 @@ sap.ui.define((function () { 'use strict'; } if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); + throw new CanceledError$1(null, config); } } @@ -5249,7 +5128,7 @@ sap.ui.define((function () { 'use strict'; config.headers.setContentType('application/x-www-form-urlencoded', false); } - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + const adapter = adapters.getAdapter(config.adapter || defaults.adapter); return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); @@ -5265,7 +5144,7 @@ sap.ui.define((function () { 'use strict'; return response; }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { + if (!isCancel$1(reason)) { throwIfCancellationRequested(config); // Transform response data @@ -5283,7 +5162,7 @@ sap.ui.define((function () { 'use strict'; }); } - const VERSION = "1.7.7"; + const VERSION$1 = "1.7.7"; const validators$1 = {}; @@ -5307,15 +5186,15 @@ sap.ui.define((function () { 'use strict'; */ validators$1.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return (value, opt, opts) => { if (validator === false) { - throw new AxiosError( + throw new AxiosError$1( formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED + AxiosError$1.ERR_DEPRECATED ); } @@ -5346,7 +5225,7 @@ sap.ui.define((function () { 'use strict'; function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE); } const keys = Object.keys(options); let i = keys.length; @@ -5357,12 +5236,12 @@ sap.ui.define((function () { 'use strict'; const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION); } } } @@ -5381,12 +5260,12 @@ sap.ui.define((function () { 'use strict'; * * @return {Axios} A new instance of Axios */ - class Axios { + let Axios$1 = class Axios { constructor(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() + request: new InterceptorManager(), + response: new InterceptorManager() }; } @@ -5435,7 +5314,7 @@ sap.ui.define((function () { 'use strict'; config = configOrUrl || {}; } - config = mergeConfig(this.defaults, config); + config = mergeConfig$1(this.defaults, config); const {transitional, paramsSerializer, headers} = config; @@ -5549,17 +5428,17 @@ sap.ui.define((function () { 'use strict'; } getUri(config) { - config = mergeConfig(this.defaults, config); + config = mergeConfig$1(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.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { + Axios$1.prototype[method] = function(url, config) { + return this.request(mergeConfig$1(config || {}, { method, url, data: (config || {}).data @@ -5572,7 +5451,7 @@ sap.ui.define((function () { 'use strict'; function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { + return this.request(mergeConfig$1(config || {}, { method, headers: isForm ? { 'Content-Type': 'multipart/form-data' @@ -5583,13 +5462,11 @@ sap.ui.define((function () { 'use strict'; }; } - Axios.prototype[method] = generateHTTPMethod(); + Axios$1.prototype[method] = generateHTTPMethod(); - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); + Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true); }); - var Axios$1 = Axios; - /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * @@ -5597,7 +5474,7 @@ sap.ui.define((function () { 'use strict'; * * @returns {CancelToken} */ - class CancelToken { + let CancelToken$1 = class CancelToken { constructor(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); @@ -5645,7 +5522,7 @@ sap.ui.define((function () { 'use strict'; return; } - token.reason = new CanceledError(message, config, request); + token.reason = new CanceledError$1(message, config, request); resolvePromise(token.reason); }); } @@ -5718,9 +5595,7 @@ sap.ui.define((function () { 'use strict'; cancel }; } - } - - var CancelToken$1 = CancelToken; + }; /** * Syntactic sugar for invoking a function and expanding an array for arguments. @@ -5743,7 +5618,7 @@ sap.ui.define((function () { 'use strict'; * * @returns {Function} */ - function spread(callback) { + function spread$1(callback) { return function wrap(arr) { return callback.apply(null, arr); }; @@ -5756,11 +5631,11 @@ sap.ui.define((function () { 'use strict'; * * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ - function isAxiosError(payload) { + function isAxiosError$1(payload) { return utils$1.isObject(payload) && (payload.isAxiosError === true); } - const HttpStatusCode = { + const HttpStatusCode$1 = { Continue: 100, SwitchingProtocols: 101, Processing: 102, @@ -5826,12 +5701,10 @@ sap.ui.define((function () { 'use strict'; NetworkAuthenticationRequired: 511, }; - Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; + Object.entries(HttpStatusCode$1).forEach(([key, value]) => { + HttpStatusCode$1[value] = key; }); - var HttpStatusCode$1 = HttpStatusCode; - /** * Create an instance of Axios * @@ -5851,27 +5724,27 @@ sap.ui.define((function () { 'use strict'; // Factory for creating new instances instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); + return createInstance(mergeConfig$1(defaultConfig, instanceConfig)); }; return instance; } // Create the default instance to be exported - const axios = createInstance(defaults$1); + const axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios$1; // Expose Cancel & CancelToken - axios.CanceledError = CanceledError; + axios.CanceledError = CanceledError$1; axios.CancelToken = CancelToken$1; - axios.isCancel = isCancel; - axios.VERSION = VERSION; - axios.toFormData = toFormData; + axios.isCancel = isCancel$1; + axios.VERSION = VERSION$1; + axios.toFormData = toFormData$1; // Expose AxiosError class - axios.AxiosError = AxiosError; + axios.AxiosError = AxiosError$1; // alias for CanceledError for backward compatibility axios.Cancel = axios.CanceledError; @@ -5881,13 +5754,13 @@ sap.ui.define((function () { 'use strict'; return Promise.all(promises); }; - axios.spread = spread; + axios.spread = spread$1; // Expose isAxiosError - axios.isAxiosError = isAxiosError; + axios.isAxiosError = isAxiosError$1; // Expose mergeConfig - axios.mergeConfig = mergeConfig; + axios.mergeConfig = mergeConfig$1; axios.AxiosHeaders = AxiosHeaders$1; @@ -5899,10 +5772,48 @@ sap.ui.define((function () { 'use strict'; axios.default = axios; - var axios_1 = axios; - - try { Object.defineProperty(axios_1, "__" + "esModule", { value: true }); axios_1.default = axios_1; } catch (ex) {} - - return axios_1; + // 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; + + try { Object.defineProperty(axios, "__" + "esModule", { value: true }); axios.default = axios; } 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 = axios; + 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 }); })); diff --git a/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js b/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js index 5545315a4..5e0f1b863 100644 --- a/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js +++ b/packages/ui5-tooling-modules/test/__snap__/2c2c8b93/luxon.js @@ -1,366 +1,234 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; - 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); - } - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - _setPrototypeOf(subClass, superClass); - } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); + // 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()}`); + } } - 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 InvalidIntervalError extends LuxonError { + constructor(reason) { + super(`Invalid Interval: ${reason.toMessage()}`); } } - 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; - }; + + /** + * @private + */ + class InvalidDurationError extends LuxonError { + constructor(reason) { + super(`Invalid Duration: ${reason.toMessage()}`); } - return _construct.apply(null, arguments); } - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; + + /** + * @private + */ + class ConflictingSpecificationError extends LuxonError {} + + /** + * @private + */ + class InvalidUnitError extends LuxonError { + constructor(unit) { + super(`Invalid unit ${unit}`); + } } - 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++] - }; - }; + + /** + * @private + */ + class InvalidArgumentError extends LuxonError {} + + /** + * @private + */ + class ZoneIsAbstractError extends LuxonError { + constructor() { + super("Zone is an abstract class"); } - 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 = { + } + + /** + * @private + */ + + const n = "numeric", + s = "short", + l = "long"; + + const DATE_SHORT = { year: n, month: n, - day: n + day: n, }; - var DATE_MED = { + + const DATE_MED = { year: n, month: s, - day: n + day: n, }; - var DATE_MED_WITH_WEEKDAY = { + + const DATE_MED_WITH_WEEKDAY = { year: n, month: s, day: n, - weekday: s + weekday: s, }; - var DATE_FULL = { + + const DATE_FULL = { year: n, month: l, - day: n + day: n, }; - var DATE_HUGE = { + + const DATE_HUGE = { year: n, month: l, day: n, - weekday: l + weekday: l, }; - var TIME_SIMPLE = { + + const TIME_SIMPLE = { hour: n, - minute: n + minute: n, }; - var TIME_WITH_SECONDS = { + + const TIME_WITH_SECONDS = { hour: n, minute: n, - second: n + second: n, }; - var TIME_WITH_SHORT_OFFSET = { + + const TIME_WITH_SHORT_OFFSET = { hour: n, minute: n, second: n, - timeZoneName: s + timeZoneName: s, }; - var TIME_WITH_LONG_OFFSET = { + + const TIME_WITH_LONG_OFFSET = { hour: n, minute: n, second: n, - timeZoneName: l + timeZoneName: l, }; - var TIME_24_SIMPLE = { + + const TIME_24_SIMPLE = { hour: n, minute: n, - hourCycle: "h23" + hourCycle: "h23", }; - var TIME_24_WITH_SECONDS = { + + const TIME_24_WITH_SECONDS = { hour: n, minute: n, second: n, - hourCycle: "h23" + hourCycle: "h23", }; - var TIME_24_WITH_SHORT_OFFSET = { + + const TIME_24_WITH_SHORT_OFFSET = { hour: n, minute: n, second: n, hourCycle: "h23", - timeZoneName: s + timeZoneName: s, }; - var TIME_24_WITH_LONG_OFFSET = { + + const TIME_24_WITH_LONG_OFFSET = { hour: n, minute: n, second: n, hourCycle: "h23", - timeZoneName: l + timeZoneName: l, }; - var DATETIME_SHORT = { + + const DATETIME_SHORT = { year: n, month: n, day: n, hour: n, - minute: n + minute: n, }; - var DATETIME_SHORT_WITH_SECONDS = { + + const DATETIME_SHORT_WITH_SECONDS = { year: n, month: n, day: n, hour: n, minute: n, - second: n + second: n, }; - var DATETIME_MED = { + + const DATETIME_MED = { year: n, month: s, day: n, hour: n, - minute: n + minute: n, }; - var DATETIME_MED_WITH_SECONDS = { + + const DATETIME_MED_WITH_SECONDS = { year: n, month: s, day: n, hour: n, minute: n, - second: n + second: n, }; - var DATETIME_MED_WITH_WEEKDAY = { + + const DATETIME_MED_WITH_WEEKDAY = { year: n, month: s, day: n, weekday: s, hour: n, - minute: n + minute: n, }; - var DATETIME_FULL = { + + const DATETIME_FULL = { year: n, month: l, day: n, hour: n, minute: n, - timeZoneName: s + timeZoneName: s, }; - var DATETIME_FULL_WITH_SECONDS = { + + const DATETIME_FULL_WITH_SECONDS = { year: n, month: l, day: n, hour: n, minute: n, second: n, - timeZoneName: s + timeZoneName: s, }; - var DATETIME_HUGE = { + + const DATETIME_HUGE = { year: n, month: l, day: n, weekday: l, hour: n, minute: n, - timeZoneName: l + timeZoneName: l, }; - var DATETIME_HUGE_WITH_SECONDS = { + + const DATETIME_HUGE_WITH_SECONDS = { year: n, month: l, day: n, @@ -368,103 +236,165 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; hour: n, minute: n, second: n, - timeZoneName: l + timeZoneName: l, }; - var Zone = (function () { - function Zone() {} - var _proto = Zone.prototype; - _proto.offsetName = function offsetName(ts, opts) { + + /** + * @interface + */ + class Zone { + /** + * The type of zone + * @abstract + * @type {string} + */ + get type() { throw new ZoneIsAbstractError(); - }; - _proto.formatOffset = function formatOffset(ts, format) { + } + + /** + * The name of this zone. + * @abstract + * @type {string} + */ + get name() { throw new ZoneIsAbstractError(); - }; - _proto.offset = function offset(ts) { + } + + /** + * 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(); - }; - _proto.equals = function equals(otherZone) { + } + + /** + * 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(); - }; - _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; + } + + /** + * 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) { + 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) { + throw new ZoneIsAbstractError(); + } + + /** + * Return whether this Zone is equal to another zone + * @abstract + * @param {Zone} otherZone - the zone to compare + * @return {boolean} + */ + equals(otherZone) { + throw new ZoneIsAbstractError(); + } + + /** + * Return whether this Zone is valid. + * @abstract + * @type {boolean} + */ + get isValid() { + 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 }) { return parseZoneInfo(ts, format, locale); - }; - _proto.formatOffset = function formatOffset$1(ts, format) { + } + + /** @override **/ + formatOffset(ts, format) { return formatOffset(this.offset(ts), format); - }; - _proto.offset = function offset(ts) { + } + + /** @override **/ + offset(ts) { return -new Date(ts).getTimezoneOffset(); - }; - _proto.equals = function equals(otherZone) { + } + + /** @override **/ + equals(otherZone) { return otherZone.type === "system"; - }; - _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 = {}; + } + + /** @override **/ + get isValid() { + return true; + } + } + + let dtfCache = {}; function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat("en-US", { @@ -476,30 +406,36 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; hour: "2-digit", minute: "2-digit", second: "2-digit", - era: "short" + era: "short", }); } return dtfCache[zone]; } - var typeToPos = { + + const typeToPos = { year: 0, month: 1, day: 2, era: 3, hour: 4, minute: 5, - second: 6 + second: 6, }; + function hackyOffset(dtf, date) { - 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]; + 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; return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; } + function partsOffset(dtf, date) { - 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]; + const formatted = dtf.formatToParts(date); + const filled = []; + for (let i = 0; i < formatted.length; i++) { + const { type, value } = formatted[i]; + const pos = typeToPos[type]; + if (type === "era") { filled[pos] = value; } else if (!isUndefined(pos)) { @@ -508,156 +444,227 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return filled; } - var ianaZoneCache = {}; - var IANAZone = (function (_Zone) { - _inheritsLoose(IANAZone, _Zone); - IANAZone.create = function create(name) { + + 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) { if (!ianaZoneCache[name]) { ianaZoneCache[name] = new IANAZone(name); } return ianaZoneCache[name]; - }; - IANAZone.resetCache = function resetCache() { + } + + /** + * Reset local caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCache() { ianaZoneCache = {}; dtfCache = {}; - }; - IANAZone.isValidSpecifier = function isValidSpecifier(s) { + } + + /** + * 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) { return this.isValidZone(s); - }; - IANAZone.isValidZone = function isValidZone(zone) { + } + + /** + * 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) { 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; } - }; - 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; + } + + 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 }) { return parseZoneInfo(ts, format, locale, this.name); - }; - _proto.formatOffset = function formatOffset$1(ts, format) { + } + + /** + * 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) { return formatOffset(this.offset(ts), format); - }; - _proto.offset = function offset(ts) { - var date = new Date(ts); + } + + /** + * 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); + if (isNaN(date)) return NaN; - 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]; + + const dtf = makeDTF(this.name); + let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts + ? partsOffset(dtf, date) + : hackyOffset(dtf, date); + if (adOrBc === "BC") { year = -Math.abs(year) + 1; } - var adjustedHour = hour === 24 ? 0 : hour; - var asUTC = objToLocalTS({ - year: year, - month: month, - day: day, + + // 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, hour: adjustedHour, - minute: minute, - second: second, - millisecond: 0 + minute, + second, + millisecond: 0, }); - var asTS = +date; - var over = asTS % 1000; + + let asTS = +date; + const over = asTS % 1000; asTS -= over >= 0 ? over : 1000 + over; return (asUTC - asTS) / (60 * 1000); - }; - _proto.equals = function equals(otherZone) { + } + + /** + * Return whether this Zone is equal to another zone + * @override + * @param {Zone} otherZone - the zone to compare + * @return {boolean} + */ + equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; - }; - _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]; + } + + /** + * 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]; if (!dtf) { dtf = new Intl.ListFormat(locString, opts); intlLFCache[key] = dtf; } return dtf; } - var intlDTCache = {}; - function getCachedDTF(locString, opts) { - if (opts === void 0) { - opts = {}; - } - var key = JSON.stringify([locString, opts]); - var dtf = intlDTCache[key]; + let intlDTCache = {}; + function getCachedDTF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlDTCache[key]; if (!dtf) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache[key] = dtf; } return dtf; } - var intlNumCache = {}; - function getCachedINF(locString, opts) { - if (opts === void 0) { - opts = {}; - } - var key = JSON.stringify([locString, opts]); - var inf = intlNumCache[key]; + let intlNumCache = {}; + function getCachedINF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let inf = intlNumCache[key]; if (!inf) { inf = new Intl.NumberFormat(locString, opts); intlNumCache[key] = inf; } return inf; } - 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]; + let intlRelCache = {}; + function getCachedRTF(locString, opts = {}) { + const {base, ...cacheKeyOpts} = opts; + const key = JSON.stringify([locString, cacheKeyOpts]); + let inf = intlRelCache[key]; if (!inf) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache[key] = inf; } return inf; } - var sysLocaleCache = null; + let sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; @@ -666,36 +673,36 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return sysLocaleCache; } } - var weekInfoCache = {}; + let weekInfoCache = {}; function getCachedWeekInfo(locString) { - var data = weekInfoCache[locString]; + let data = weekInfoCache[locString]; if (!data) { - var locale = new Intl.Locale(locString); + const locale = new Intl.Locale(locString); data = ("getWeekInfo" in locale) ? locale.getWeekInfo() : locale.weekInfo; weekInfoCache[locString] = data; } return data; } function parseLocaleString(localeStr) { - var xIndex = localeStr.indexOf("-x-"); + const xIndex = localeStr.indexOf("-x-"); if (xIndex !== -1) { localeStr = localeStr.substring(0, xIndex); } - var uIndex = localeStr.indexOf("-u-"); + const uIndex = localeStr.indexOf("-u-"); if (uIndex === -1) { return [localeStr]; } else { - var options; - var selectedStr; + let options; + let selectedStr; try { options = getCachedDTF(localeStr).resolvedOptions(); selectedStr = localeStr; } catch (e) { - var smaller = localeStr.substring(0, uIndex); + const smaller = localeStr.substring(0, uIndex); options = getCachedDTF(smaller).resolvedOptions(); selectedStr = smaller; } - var _options = options, numberingSystem = _options.numberingSystem, calendar = _options.calendar; + const {numberingSystem, calendar} = options; return [selectedStr, numberingSystem, calendar]; } } @@ -705,10 +712,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 { @@ -716,23 +723,23 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } function mapMonths(f) { - var ms = []; - for (var i = 1; i <= 12; i++) { - var dt = DateTime.utc(2009, i, 1); + const ms = []; + for (let i = 1; i <= 12; i++) { + const dt = DateTime.utc(2009, i, 1); ms.push(f(dt)); } return ms; } function mapWeekdays(f) { - var ms = []; - for (var i = 1; i <= 7; i++) { - var dt = DateTime.utc(2016, 11, 13 + i); + const ms = []; + for (let i = 1; i <= 7; i++) { + const dt = DateTime.utc(2016, 11, 13 + i); ms.push(f(dt)); } return ms; } function listStuff(loc, length, englishFn, intlFn) { - var mode = loc.listingMode(); + const mode = loc.listingMode(); if (mode === "error") { return null; } else if (mode === "en") { @@ -748,43 +755,40 @@ 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"; } } - var PolyNumberFormatter = (function () { - function PolyNumberFormatter(intl, forceSimple, opts) { + class PolyNumberFormatter { + constructor(intl, forceSimple, opts) { this.padTo = opts.padTo || 0; this.floor = opts.floor || false; - opts.padTo; - opts.floor; - var otherOpts = _objectWithoutPropertiesLoose(opts, _excluded2); + const {padTo, floor, ...otherOpts} = opts; if (!forceSimple || Object.keys(otherOpts).length > 0) { - var intlOpts = _extends({ - useGrouping: false - }, opts); + const intlOpts = { + useGrouping: false, + ...opts + }; if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo; this.inf = getCachedINF(intl, intlOpts); } } - var _proto = PolyNumberFormatter.prototype; - _proto.format = function format(i) { + format(i) { if (this.inf) { - var fixed = this.floor ? Math.floor(i) : i; + const fixed = this.floor ? Math.floor(i) : i; return this.inf.format(fixed); } else { - var _fixed = this.floor ? Math.floor(i) : roundTo(i, 3); - return padStart(_fixed, this.padTo); + const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); + return padStart(fixed, this.padTo); } - }; - return PolyNumberFormatter; - })(); - var PolyDateFormatter = (function () { - function PolyDateFormatter(dt, intl, opts) { + } + } + class PolyDateFormatter { + constructor(dt, intl, opts) { this.opts = opts; this.originalZone = undefined; - var z = undefined; + let z = undefined; if (this.opts.timeZone) { this.dt = dt; } else if (dt.zone.type === "fixed") { - var gmtOffset = -1 * (dt.offset / 60); - var offsetZ = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset; + const gmtOffset = -1 * (dt.offset / 60); + const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { z = offsetZ; this.dt = dt; @@ -807,103 +811,95 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); this.originalZone = dt.zone; } - var intlOpts = _extends({}, this.opts); + const intlOpts = { + ...this.opts + }; intlOpts.timeZone = intlOpts.timeZone || z; this.dtf = getCachedDTF(intl, intlOpts); } - var _proto2 = PolyDateFormatter.prototype; - _proto2.format = function format() { + format() { if (this.originalZone) { - return this.formatToParts().map(function (_ref) { - var value = _ref.value; - return value; - }).join(""); + return this.formatToParts().map(({value}) => value).join(""); } return this.dtf.format(this.dt.toJSDate()); - }; - _proto2.formatToParts = function formatToParts() { - var _this = this; - var parts = this.dtf.formatToParts(this.dt.toJSDate()); + } + formatToParts() { + const parts = this.dtf.formatToParts(this.dt.toJSDate()); if (this.originalZone) { - return parts.map(function (part) { + return parts.map(part => { if (part.type === "timeZoneName") { - var offsetName = _this.originalZone.offsetName(_this.dt.ts, { - locale: _this.dt.locale, - format: _this.opts.timeZoneName + const offsetName = this.originalZone.offsetName(this.dt.ts, { + locale: this.dt.locale, + format: this.opts.timeZoneName }); - return _extends({}, part, { + return { + ...part, value: offsetName - }); + }; } else { return part; } }); } return parts; - }; - _proto2.resolvedOptions = function resolvedOptions() { + } + resolvedOptions() { return this.dtf.resolvedOptions(); - }; - return PolyDateFormatter; - })(); - var PolyRelFormatter = (function () { - function PolyRelFormatter(intl, isEnglish, opts) { - this.opts = _extends({ - style: "long" - }, opts); + } + } + class PolyRelFormatter { + constructor(intl, isEnglish, opts) { + this.opts = { + style: "long", + ...opts + }; if (!isEnglish && hasRelative()) { this.rtf = getCachedRTF(intl, opts); } } - var _proto3 = PolyRelFormatter.prototype; - _proto3.format = function format(count, unit) { + format(count, unit) { if (this.rtf) { return this.rtf.format(count, unit); } else { return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); } - }; - _proto3.formatToParts = function formatToParts(count, unit) { + } + formatToParts(count, unit) { if (this.rtf) { return this.rtf.formatToParts(count, unit); } else { return []; } - }; - return PolyRelFormatter; - })(); - var fallbackWeekSettings = { + } + } + const fallbackWeekSettings = { firstDay: 1, minimalDays: 4, weekend: [6, 7] }; - var Locale = (function () { - Locale.fromOpts = function fromOpts(opts) { + class Locale { + static fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN); - }; - 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; + } + 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; return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); - }; - Locale.resetCache = function resetCache() { + } + static resetCache() { sysLocaleCache = null; intlDTCache = {}; intlNumCache = {}; intlRelCache = {}; - }; - Locale.fromObject = function fromObject(_temp) { - var _ref2 = _temp === void 0 ? {} : _temp, locale = _ref2.locale, numberingSystem = _ref2.numberingSystem, outputCalendar = _ref2.outputCalendar, weekSettings = _ref2.weekSettings; + } + static fromObject({locale, numberingSystem, outputCalendar, weekSettings} = {}) { return Locale.create(locale, numberingSystem, outputCalendar, weekSettings); - }; - function Locale(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { - var _parseLocaleString = parseLocaleString(locale), parsedLocale = _parseLocaleString[0], parsedNumberingSystem = _parseLocaleString[1], parsedOutputCalendar = _parseLocaleString[2]; + } + constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { + const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; @@ -922,62 +918,53 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; this.specifiedLocale = specifiedLocale; this.fastNumbersCached = null; } - 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"); + 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"); return isActuallyEn && hasNoWeirdness ? "en" : "intl"; - }; - _proto4.clone = function clone(alts) { + } + 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); } - }; - _proto4.redefaultToEN = function redefaultToEN(alts) { - if (alts === void 0) { - alts = {}; - } - return this.clone(_extends({}, alts, { + } + redefaultToEN(alts = {}) { + return this.clone({ + ...alts, defaultToEN: true - })); - }; - _proto4.redefaultToSystem = function redefaultToSystem(alts) { - if (alts === void 0) { - alts = {}; - } - return this.clone(_extends({}, alts, { + }); + } + redefaultToSystem(alts = {}) { + return this.clone({ + ...alts, defaultToEN: false - })); - }; - _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 ? { + }); + } + months(length, format = false) { + return listStuff(this, length, months, () => { + const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; - if (!_this2.monthsCache[formatStr][length]) { - _this2.monthsCache[formatStr][length] = mapMonths(function (dt) { - return _this2.extract(dt, intl, "month"); - }); + if (!this.monthsCache[formatStr][length]) { + this.monthsCache[formatStr][length] = mapMonths(dt => this.extract(dt, intl, "month")); } - return _this2.monthsCache[formatStr][length]; + return this.monthsCache[formatStr][length]; }); - }; - _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 ? { + } + weekdays(length, format = false) { + return listStuff(this, length, weekdays, () => { + const intl = format ? { weekday: length, year: "numeric", month: "long", @@ -985,79 +972,55 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } : { weekday: length }, formatStr = format ? "format" : "standalone"; - if (!_this3.weekdaysCache[formatStr][length]) { - _this3.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) { - return _this3.extract(dt, intl, "weekday"); - }); + if (!this.weekdaysCache[formatStr][length]) { + this.weekdaysCache[formatStr][length] = mapWeekdays(dt => this.extract(dt, intl, "weekday")); } - return _this3.weekdaysCache[formatStr][length]; + return this.weekdaysCache[formatStr][length]; }); - }; - _proto4.meridiems = function meridiems$1() { - var _this4 = this; - return listStuff(this, undefined, function () { - return meridiems; - }, function () { - if (!_this4.meridiemCache) { - var intl = { + } + meridiems() { + return listStuff(this, undefined, () => meridiems, () => { + if (!this.meridiemCache) { + const intl = { hour: "numeric", hourCycle: "h12" }; - _this4.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) { - return _this4.extract(dt, intl, "dayperiod"); - }); + this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(dt => this.extract(dt, intl, "dayperiod")); } - return _this4.meridiemCache; + return this.meridiemCache; }); - }; - _proto4.eras = function eras$1(length) { - var _this5 = this; - return listStuff(this, length, eras, function () { - var intl = { + } + eras(length) { + return listStuff(this, length, eras, () => { + const intl = { era: length }; - 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"); - }); + if (!this.eraCache[length]) { + this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt => this.extract(dt, intl, "era")); } - 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; + return this.eraCache[length]; }); + } + 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; - }; - _proto4.numberFormatter = function numberFormatter(opts) { - if (opts === void 0) { - opts = {}; - } + } + numberFormatter(opts = {}) { return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); - }; - _proto4.dtFormatter = function dtFormatter(dt, intlOpts) { - if (intlOpts === void 0) { - intlOpts = {}; - } + } + dtFormatter(dt, intlOpts = {}) { return new PolyDateFormatter(dt, this.intl, intlOpts); - }; - _proto4.relFormatter = function relFormatter(opts) { - if (opts === void 0) { - opts = {}; - } + } + relFormatter(opts = {}) { return new PolyRelFormatter(this.intl, this.isEnglish(), opts); - }; - _proto4.listFormatter = function listFormatter(opts) { - if (opts === void 0) { - opts = {}; - } + } + listFormatter(opts = {}) { return getCachedLF(this.intl, opts); - }; - _proto4.isEnglish = function isEnglish() { + } + isEnglish() { return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); - }; - _proto4.getWeekSettings = function getWeekSettings() { + } + getWeekSettings() { if (this.weekSettings) { return this.weekSettings; } else if (!hasLocaleWeekInfo()) { @@ -1065,191 +1028,276 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { return getCachedWeekInfo(this.locale); } - }; - _proto4.getStartOfWeek = function getStartOfWeek() { + } + getStartOfWeek() { return this.getWeekSettings().firstDay; - }; - _proto4.getMinDaysInFirstWeek = function getMinDaysInFirstWeek() { + } + getMinDaysInFirstWeek() { return this.getWeekSettings().minimalDays; - }; - _proto4.getWeekendDays = function getWeekendDays() { + } + getWeekendDays() { return this.getWeekSettings().weekend; - }; - _proto4.equals = function equals(other) { + } + equals(other) { return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; - }; - _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) { + } + 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) { return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); - }; - FixedOffsetZone.parseSpecifier = function parseSpecifier(s) { + } + + /** + * 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) { if (s) { - var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); if (r) { return new FixedOffsetZone(signedOffset(r[1], r[2])); } } return null; - }; - function FixedOffsetZone(offset) { - var _this; - _this = _Zone.call(this) || this; - _this.fixed = offset; - return _this; - } - var _proto = FixedOffsetZone.prototype; - _proto.offsetName = function offsetName() { + } + + 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() { return this.name; - }; - _proto.formatOffset = function formatOffset$1(ts, format) { + } + + /** + * 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) { return formatOffset(this.fixed, format); - }; - _proto.offset = function offset() { + } + + /** + * 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() { return this.fixed; - }; - _proto.equals = function equals(otherZone) { + } + + /** + * 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) { return otherZone.type === "fixed" && otherZone.fixed === this.fixed; - }; - _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 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() { return null; - }; - _proto.formatOffset = function formatOffset() { + } + + /** @override **/ + formatOffset() { return ""; - }; - _proto.offset = function offset() { + } + + /** @override **/ + offset() { return NaN; - }; - _proto.equals = function equals() { + } + + /** @override **/ + equals() { return false; - }; - _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); + } + + /** @override **/ + get isValid() { + return false; + } + } + + /** + * @private + */ + + function normalizeZone(input, defaultZone) { if (isUndefined(input) || input === null) { return defaultZone; } else if (input instanceof Zone) { return input; } else if (isString(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); + 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); } else if (isNumber(input)) { return FixedOffsetZone.instance(input); - } else if (typeof input === "object" && ("offset" in input) && typeof input.offset === "function") { + } 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 return input; } else { return new InvalidZone(input); } } - var numberingSystems = { - arab: "[٠-٩]", - arabext: "[۰-۹]", - bali: "[᭐-᭙]", - beng: "[০-৯]", - deva: "[०-९]", - fullwide: "[0-9]", - gujr: "[૦-૯]", + + const numberingSystems = { + arab: "[\u0660-\u0669]", + arabext: "[\u06F0-\u06F9]", + bali: "[\u1B50-\u1B59]", + beng: "[\u09E6-\u09EF]", + deva: "[\u0966-\u096F]", + fullwide: "[\uFF10-\uFF19]", + gujr: "[\u0AE6-\u0AEF]", hanidec: "[〇|一|二|三|四|五|六|七|八|九]", - khmr: "[០-៩]", - knda: "[೦-೯]", - laoo: "[໐-໙]", - limb: "[᥆-᥏]", - mlym: "[൦-൯]", - mong: "[᠐-᠙]", - mymr: "[၀-၉]", - orya: "[୦-୯]", - tamldec: "[௦-௯]", - telu: "[౦-౯]", - thai: "[๐-๙]", - tibt: "[༠-༩]", - latn: "\\d" + 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", }; - var numberingSystemsUTF16 = { + + const numberingSystemsUTF16 = { arab: [1632, 1641], arabext: [1776, 1785], bali: [6992, 7001], @@ -1268,20 +1316,23 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; tamldec: [3046, 3055], telu: [3174, 3183], thai: [3664, 3673], - tibt: [3872, 3881] + tibt: [3872, 3881], }; - var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); + + const hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); + function parseDigits(str) { - var value = parseInt(str, 10); + let value = parseInt(str, 10); if (isNaN(value)) { value = ""; - for (var i = 0; i < str.length; i++) { - var code = str.charCodeAt(i); + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + if (str[i].search(numberingSystems.hanidec) !== -1) { value += hanidecChars.indexOf(str[i]); } else { - for (var key in numberingSystemsUTF16) { - var _numberingSystemsUTF = numberingSystemsUTF16[key], min = _numberingSystemsUTF[0], max = _numberingSystemsUTF[1]; + for (const key in numberingSystemsUTF16) { + const [min, max] = numberingSystemsUTF16[key]; if (code >= min && code <= max) { value += code - min; } @@ -1293,153 +1344,262 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return value; } } - var digitRegexCache = {}; + + // cache of {numberingSystem: {append: regex}} + let digitRegexCache = {}; function resetDigitRegexCache() { digitRegexCache = {}; } - function digitRegex(_ref, append) { - var numberingSystem = _ref.numberingSystem; - if (append === void 0) { - append = ""; - } - var ns = numberingSystem || "latn"; + + function digitRegex({ numberingSystem }, append = "") { + const 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]; } - 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() { + + 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() { Locale.resetCache(); IANAZone.resetCache(); DateTime.resetCache(); resetDigitRegexCache(); - }; - _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) { + } + } + + class Invalid { + constructor(reason, explanation) { this.reason = reason; this.explanation = explanation; } - var _proto = Invalid.prototype; - _proto.toMessage = function toMessage() { + + toMessage() { if (this.explanation) { - return this.reason + ": " + this.explanation; + return `${this.reason}: ${this.explanation}`; } else { return this.reason; } - }; - 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]; + } + } + + 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]; + 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) { - var d = new Date(Date.UTC(year, month - 1, day)); + const d = new Date(Date.UTC(year, month - 1, day)); + if (year < 100 && year >= 0) { d.setUTCFullYear(d.getUTCFullYear() - 1900); } - var js = d.getUTCDay(); + + const 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) { - var table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex(function (i) { - return i < ordinal; - }), day = ordinal - table[month0]; - return { - month: month0 + 1, - day: day - }; + const table = isLeapYear(year) ? leapLadder : nonLeapLadder, + month0 = table.findIndex((i) => i < ordinal), + day = ordinal - table[month0]; + return { month: month0 + 1, day }; } + function isoWeekdayToLocal(isoWeekday, startOfWeek) { - return (isoWeekday - startOfWeek + 7) % 7 + 1; + return ((isoWeekday - startOfWeek + 7) % 7) + 1; } - 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; + + /** + * @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; + if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); @@ -1449,21 +1609,18 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { weekYear = year; } - return _extends({ - weekYear: weekYear, - weekNumber: weekNumber, - weekday: weekday - }, timeObject(gregObj)); + + return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; } - 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; + + 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; + if (ordinal < 1) { year = weekYear - 1; ordinal += daysInYear(year); @@ -1473,36 +1630,42 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { year = weekYear; } - var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal.month, day = _uncomputeOrdinal.day; - return _extends({ - year: year, - month: month, - day: day - }, timeObject(weekData)); + + const { month, day } = uncomputeOrdinal(year, ordinal); + return { year, month, day, ...timeObject(weekData) }; } + function gregorianToOrdinal(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)); + const { year, month, day } = gregData; + const ordinal = computeOrdinal(year, month, day); + return { year, ordinal, ...timeObject(gregData) }; } + function ordinalToGregorian(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)); + const { year, ordinal } = ordinalData; + const { month, day } = uncomputeOrdinal(year, ordinal); + return { year, month, 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) { - var hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); + const hasLocaleWeekData = + !isUndefined(obj.localWeekday) || + !isUndefined(obj.localWeekNumber) || + !isUndefined(obj.localWeekYear); if (hasLocaleWeekData) { - var hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); + const 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; @@ -1512,23 +1675,22 @@ 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, 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); + + 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); + if (!validYear) { return unitOutOfRange("weekYear", obj.weekYear); } else if (!validWeek) { @@ -1537,16 +1699,23 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return unitOutOfRange("weekday", obj.weekday); } else return false; } + function hasInvalidOrdinalData(obj) { - var validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); + const 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) { - var validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); + const 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) { @@ -1555,9 +1724,16 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return unitOutOfRange("day", obj.day); } else return false; } + function hasInvalidTimeData(obj) { - 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); + 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); + if (!validHour) { return unitOutOfRange("hour", hour); } else if (!validMinute) { @@ -1568,21 +1744,42 @@ 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; @@ -1590,22 +1787,31 @@ 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(function (best, next) { - var pair = [by(next), next]; + return arr.reduce((best, next) => { + const pair = [by(next), next]; if (!best) { return pair; } else if (compare(best[0], pair[0]) === best[0]) { @@ -1615,45 +1821,54 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }, null)[1]; } + function pick(obj, keys) { - return keys.reduce(function (a, k) { + return keys.reduce((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(function (v) { - return !integerBetween(v, 1, 7); - })) { + if ( + !integerBetween(settings.firstDay, 1, 7) || + !integerBetween(settings.minimalDays, 1, 7) || + !Array.isArray(settings.weekend) || + settings.weekend.some((v) => !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) { - if (n === void 0) { - n = 2; - } - var isNeg = input < 0; - var padded; + + function padStart(input, n = 2) { + const isNeg = input < 0; + let padded; if (isNeg) { padded = "-" + ("" + -input).padStart(n, "0"); } else { @@ -1661,6 +1876,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return padded; } + function parseInteger(string) { if (isUndefined(string) || string === null || string === "") { return undefined; @@ -1668,6 +1884,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return parseInt(string, 10); } } + function parseFloating(string) { if (isUndefined(string) || string === null || string === "") { return undefined; @@ -1675,137 +1892,217 @@ 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 { - var f = parseFloat("0." + fraction) * 1000; + const f = parseFloat("0." + fraction) * 1000; return Math.floor(f); } } - function roundTo(number, digits, towardZero) { - if (towardZero === void 0) { - towardZero = false; - } - var factor = Math.pow(10, digits), rounder = towardZero ? Math.trunc : Math.round; + + function roundTo(number, digits, towardZero = false) { + const factor = 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) { - var modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; + const 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) { - var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); + 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 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) { - var fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); + const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); return -fwdlw + minDaysInFirstWeek - 1; } - 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); + + function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { + const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); + const 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; } - 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" - }; + + // 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", + }; + if (timeZone) { intlOpts.timeZone = timeZone; } - var modified = _extends({ - timeZoneName: offsetFormat - }, intlOpts); - var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) { - return m.type.toLowerCase() === "timezonename"; - }); + + const modified = { timeZoneName: offsetFormat, ...intlOpts }; + + const parsed = new Intl.DateTimeFormat(locale, modified) + .formatToParts(date) + .find((m) => m.type.toLowerCase() === "timezonename"); return parsed ? parsed.value : null; } + + // signedOffset('-5', '30') -> -330 function signedOffset(offHourStr, offMinuteStr) { - var offHour = parseInt(offHourStr, 10); + let offHour = parseInt(offHourStr, 10); + + // don't || this because we want to preserve -0 if (Number.isNaN(offHour)) { offHour = 0; } - var offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + + const offMin = parseInt(offMinuteStr, 10) || 0, + offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; return offHour * 60 + offMinSigned; } + + // COERCION + function asNumber(value) { - var numericValue = Number(value); - if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) throw new InvalidArgumentError("Invalid unit value " + value); + const numericValue = Number(value); + if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) + throw new InvalidArgumentError(`Invalid unit value ${value}`); return numericValue; } + function normalizeObject(obj, normalizer) { - var normalized = {}; - for (var u in obj) { + const normalized = {}; + for (const u in obj) { if (hasOwnProperty(obj, u)) { - var v = obj[u]; + const 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) { - var hours = Math.trunc(Math.abs(offset / 60)), minutes = Math.trunc(Math.abs(offset % 60)), sign = offset >= 0 ? "+" : "-"; + const 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"]); } - 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"]; + + /** + * @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"]; + function months(length) { switch (length) { case "narrow": - return [].concat(monthsNarrow); + return [...monthsNarrow]; case "short": - return [].concat(monthsShort); + return [...monthsShort]; case "long": - return [].concat(monthsLong); + return [...monthsLong]; case "numeric": return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; case "2-digit": @@ -1814,59 +2111,75 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return null; } } - 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"]; + + 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"]; + function weekdays(length) { switch (length) { case "narrow": - return [].concat(weekdaysNarrow); + return [...weekdaysNarrow]; case "short": - return [].concat(weekdaysShort); + return [...weekdaysShort]; case "long": - return [].concat(weekdaysLong); + return [...weekdaysLong]; case "numeric": return ["1", "2", "3", "4", "5", "6", "7"]; default: return null; } } - var meridiems = ["AM", "PM"]; - var erasLong = ["Before Christ", "Anno Domini"]; - var erasShort = ["BC", "AD"]; - var erasNarrow = ["B", "A"]; + + const meridiems = ["AM", "PM"]; + + const erasLong = ["Before Christ", "Anno Domini"]; + + const erasShort = ["BC", "AD"]; + + const erasNarrow = ["B", "A"]; + function eras(length) { switch (length) { case "narrow": - return [].concat(erasNarrow); + return [...erasNarrow]; case "short": - return [].concat(erasShort); + return [...erasShort]; case "long": - return [].concat(erasLong); + return [...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, narrow) { - if (numeric === void 0) { - numeric = "always"; - } - if (narrow === void 0) { - narrow = false; - } - var units = { + + function formatRelativeTime(unit, count, numeric = "always", narrow = false) { + const units = { years: ["year", "yr."], quarters: ["quarter", "qtr."], months: ["month", "mo."], @@ -1874,27 +2187,40 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; days: ["day", "day", "days"], hours: ["hour", "hr."], minutes: ["minute", "min."], - seconds: ["second", "sec."] + seconds: ["second", "sec."], }; - var lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; + + const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; + if (numeric === "auto" && lastable) { - var isDay = unit === "days"; + const 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]}`; } } - 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; + + 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}`; } + function stringifyTokens(splits, tokenToString) { - var s = ""; - for (var _iterator = _createForOfIteratorHelperLoose(splits), _step; !(_step = _iterator()).done; ) { - var token = _step.value; + let s = ""; + for (const token of splits) { if (token.literal) { s += token.val; } else { @@ -1903,7 +2229,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return s; } - var _macroTokenToFormatOpts = { + + const macroTokenToFormatOpts = { D: DATE_SHORT, DD: DATE_MED, DDD: DATE_FULL, @@ -1923,26 +2250,31 @@ 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, }; - var Formatter = (function () { - Formatter.create = function create(locale, opts) { - if (opts === void 0) { - opts = {}; - } + + /** + * @private + */ + + class Formatter { + static create(locale, opts = {}) { return new Formatter(locale, opts); - }; - 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); + } + + 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); 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 = ""; @@ -1953,436 +2285,493 @@ 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; - }; - Formatter.macroTokenToFormatOpts = function macroTokenToFormatOpts(token) { - return _macroTokenToFormatOpts[token]; - }; - function Formatter(locale, formatOpts) { + } + + static macroTokenToFormatOpts(token) { + return macroTokenToFormatOpts[token]; + } + + constructor(locale, formatOpts) { this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } - var _proto = Formatter.prototype; - _proto.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) { + + formatWithSystemDefault(dt, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } - var df = this.systemLoc.dtFormatter(dt, _extends({}, this.opts, opts)); + const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts }); return df.format(); - }; - _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) { + } + + dtFormatter(dt, opts = {}) { + return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); + } + + formatDateTime(dt, opts) { return this.dtFormatter(dt, opts).format(); - }; - _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) { + } + + formatDateTimeParts(dt, opts) { return this.dtFormatter(dt, opts).formatToParts(); - }; - _proto.formatInterval = function formatInterval(interval, opts) { - var df = this.dtFormatter(interval.start, opts); + } + + formatInterval(interval, opts) { + const df = this.dtFormatter(interval.start, opts); return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); - }; - _proto.resolvedOptions = function resolvedOptions(dt, opts) { + } + + resolvedOptions(dt, opts) { return this.dtFormatter(dt, opts).resolvedOptions(); - }; - _proto.num = function num(n, p) { - if (p === void 0) { - p = 0; - } + } + + num(n, p = 0) { + // we get some perf out of doing this here, annoyingly if (this.opts.forceSimple) { return padStart(n, p); } - var opts = _extends({}, this.opts); + + const opts = { ...this.opts }; + if (p > 0) { opts.padTo = p; } + return this.loc.numberFormatter(opts).format(n); - }; - _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); - } - }; + } + + 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); + } + }; + return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); - }; - _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); + } + + 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); if (mapped) { - return _this2.num(lildur.get(mapped), token.length); + return this.num(lildur.get(mapped), token.length); } else { return token; } - }; - }, 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; - })); + }, + tokens = Formatter.parseFormat(fmt), + realTokens = tokens.reduce( + (found, { literal, val }) => (literal ? found : found.concat(val)), + [] + ), + collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)); return stringifyTokens(tokens, tokenToString(collapsed)); - }; - 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); - }; + } + } + + /* + * 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); } - function parse(s) { + + function parse(s, ...patterns) { if (s == null) { return [null, null]; } - 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); + + for (const [regex, extractor] of patterns) { + const m = regex.exec(s); if (m) { return extractor(m); } } return [null, null]; } - 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; + + function simpleParse(...keys) { + return (match, cursor) => { + const ret = {}; + let i; + for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInteger(match[cursor + i]); } return [ret, null, cursor + i]; }; } - 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 + ")?"); + + // 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})?`); + function int(match, pos, fallback) { - var m = match[pos]; + const m = match[pos]; return isUndefined(m) ? fallback : parseInteger(m); } + function extractISOYmd(match, cursor) { - var item = { + const 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) { - var item = { + const 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) { - var local = !match[cursor] && !match[cursor + 1], fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); + const 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) { - var zone = match[cursor] ? IANAZone.create(match[cursor]) : null; + const zone = match[cursor] ? IANAZone.create(match[cursor]) : null; return [{}, zone, cursor + 1]; } - 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)?)?)$/; + + // 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)?)?)$/; + function extractISODuration(match) { - 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 = { + 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 = { GMT: 0, EDT: -4 * 60, EST: -5 * 60, @@ -2391,26 +2780,51 @@ 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) { - var result = { + const 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; } - 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)))$/; + + // 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)))$/; + function extractRFC2822(match) { - 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; + const [ + , + weekdayStr, + dayStr, + monthStr, + yearStr, + hourStr, + minuteStr, + secondStr, + obsOffset, + milOffset, + offHourStr, + offMinuteStr, + ] = match, + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + + let offset; if (obsOffset) { offset = obsOffsets[obsOffset]; } else if (milOffset) { @@ -2418,167 +2832,272 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { offset = signedOffset(offHourStr, offMinuteStr); } + return [result, new FixedOffsetZone(offset)]; } + function preprocessRFC2822(s) { - return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s + .replace(/\([^()]*\)|[\n\t]/g, " ") + .replace(/(\s\s+)/g, " ") + .trim(); } - 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})$/; + + // 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})$/; + function extractRFC1123Or850(match) { - 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); + const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match, + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } + function extractASCII(match) { - 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); + const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match, + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } - 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); + + 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 + */ + 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]); } - var extractISOTimeOnly = combineExtractors(extractISOTime); + + const extractISOTimeOnly = combineExtractors(extractISOTime); + function parseISOTimeOnly(s) { return parse(s, [isoTimeOnly, extractISOTimeOnly]); } - var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); - var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); - var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); + + const sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); + const sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); + + const extractISOTimeOffsetAndIANAZone = combineExtractors( + extractISOTime, + extractISOOffset, + extractIANAZone + ); + function parseSQL(s) { - 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 - }, - 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 - } - }, 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 + 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 }, }, - 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 + 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, }, - 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 || ({})), + 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 || {}) }, 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) { - 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; + let sum = vals.milliseconds ?? 0; + for (const unit of reverseUnits.slice(1)) { if (vals[unit]) { sum += vals[unit] * matrix[unit]["milliseconds"]; } } return sum; } + + // NB: mutates parameters function normalizeValues(matrix, vals) { - var factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; - orderedUnits$1.reduceRight(function (previous, current) { + // 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) => { if (!isUndefined(vals[current])) { if (previous) { - var previousVal = vals[previous] * factor; - var conv = matrix[current][previous]; - var rollUp = Math.floor(previousVal / conv); + 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); vals[current] += rollUp * factor; vals[previous] -= rollUp * conv * factor; } @@ -2587,10 +3106,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return previous; } }, null); - orderedUnits$1.reduce(function (previous, current) { + + // 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) => { if (!isUndefined(vals[current])) { if (previous) { - var fraction = vals[previous] % 1; + const fraction = vals[previous] % 1; vals[previous] -= fraction; vals[current] += fraction * matrix[previous][current]; } @@ -2600,50 +3122,130 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }, null); } + + // Remove all properties with a value of 0 from an object function removeZeroes(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]; + const newVals = {}; + for (const [key, value] of Object.entries(vals)) { if (value !== 0) { newVals[key] = value; } } return newVals; } - var Duration = (function (_Symbol$for) { - function Duration(config) { - var accurate = config.conversionAccuracy === "longterm" || false; - var matrix = accurate ? accurateMatrix : casualMatrix; + + /** + * 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; + 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; } - Duration.fromMillis = function fromMillis(count, opts) { - return Duration.fromObject({ - milliseconds: count - }, opts); - }; - Duration.fromObject = function fromObject(obj, opts) { - if (opts === void 0) { - opts = {}; - } + + /** + * 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 = {}) { 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, }); - }; - Duration.fromDurationLike = function fromDurationLike(durationLike) { + } + + /** + * 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) { if (isNumber(durationLike)) { return Duration.fromMillis(durationLike); } else if (Duration.isDuration(durationLike)) { @@ -2651,43 +3253,85 @@ 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}` + ); } - }; - Duration.fromISO = function fromISO(text, opts) { - var _parseISODuration = parseISODuration(text), parsed = _parseISODuration[0]; + } + + /** + * 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); 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.fromISOTime = function fromISOTime(text, opts) { - var _parseISOTimeOnly = parseISOTimeOnly(text), parsed = _parseISOTimeOnly[0]; + } + + /** + * 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); if (parsed) { return Duration.fromObject(parsed, opts); } else { - 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; + return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); } + } + + /** + * 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"); } - var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { throw new InvalidDurationError(invalid); } else { - return new Duration({ - invalid: invalid - }); + return new Duration({ invalid }); } - }; - Duration.normalizeUnit = function normalizeUnit(unit) { - var normalized = ({ + } + + /** + * @private + */ + static normalizeUnit(unit) { + const normalized = { year: "years", years: "years", quarter: "quarters", @@ -2705,784 +3349,1480 @@ 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; - }; - 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 = {}; - } + } + + /** + * 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 = {}) { if (!this.isValid) return INVALID$2; - 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() { + + 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() { if (!this.isValid) return {}; - return _extends({}, this.values); - }; - _proto.toISO = function toISO() { + 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 if (!this.isValid) return null; - var s = "P"; + + let 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) s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; + 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 (s === "P") s += "T0S"; return s; - }; - _proto.toISOTime = function toISOTime(opts) { - if (opts === void 0) { - opts = {}; - } + } + + /** + * 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 = {}) { if (!this.isValid) return null; - var millis = this.toMillis(); + + const millis = this.toMillis(); if (millis < 0 || millis >= 86400000) return null; - opts = _extends({ + + opts = { suppressMilliseconds: false, suppressSeconds: false, includePrefix: false, - format: "extended" - }, opts, { - includeOffset: false - }); - var dateTime = DateTime.fromMillis(millis, { - zone: "UTC" - }); + format: "extended", + ...opts, + includeOffset: false, + }; + + const dateTime = DateTime.fromMillis(millis, { zone: "UTC" }); return dateTime.toISOTime(opts); - }; - _proto.toJSON = function toJSON() { + } + + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. + * @return {string} + */ + toJSON() { return this.toISO(); - }; - _proto.toString = function toString() { + } + + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. + * @return {string} + */ + toString() { return this.toISO(); - }; - _proto[_Symbol$for] = function () { + } + + /** + * Returns a string representation of this Duration appropriate for the REPL. + * @return {string} + */ + [Symbol.for("nodejs.util.inspect.custom")]() { 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} }`; } - }; - _proto.toMillis = function toMillis() { + } + + /** + * Returns an milliseconds value of this Duration. + * @return {number} + */ + toMillis() { if (!this.isValid) return NaN; + return durationToMillis(this.matrix, this.values); - }; - _proto.valueOf = function valueOf() { + } + + /** + * Returns an milliseconds value of this Duration. Alias of {@link toMillis} + * @return {number} + */ + valueOf() { return this.toMillis(); - }; - _proto.plus = function plus(duration) { + } + + /** + * 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) { if (!this.isValid) return this; - var dur = Duration.fromDurationLike(duration), result = {}; - for (var _i2 = 0, _orderedUnits = orderedUnits$1; _i2 < _orderedUnits.length; _i2++) { - var k = _orderedUnits[_i2]; + + const dur = Duration.fromDurationLike(duration), + result = {}; + + for (const k of orderedUnits$1) { if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { result[k] = dur.get(k) + this.get(k); } } - return clone$1(this, { - values: result - }, true); - }; - _proto.minus = function minus(duration) { + + 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) { if (!this.isValid) return this; - var dur = Duration.fromDurationLike(duration); + + const dur = Duration.fromDurationLike(duration); return this.plus(dur.negate()); - }; - _proto.mapUnits = function mapUnits(fn) { + } + + /** + * 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) { if (!this.isValid) return this; - var result = {}; - for (var _i3 = 0, _Object$keys = Object.keys(this.values); _i3 < _Object$keys.length; _i3++) { - var k = _Object$keys[_i3]; + const result = {}; + for (const k of Object.keys(this.values)) { result[k] = asNumber(fn(this.values[k], k)); } - return clone$1(this, { - values: result - }, true); - }; - _proto.get = function get(unit) { + 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 this[Duration.normalizeUnit(unit)]; - }; - _proto.set = function set(values) { + } + + /** + * "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) { if (!this.isValid) return this; - 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 - }; + + 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 }; return clone$1(this, opts); - }; - _proto.as = function as(unit) { + } + + /** + * 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) { return this.isValid ? this.shiftTo(unit).get(unit) : NaN; - }; - _proto.normalize = function normalize() { + } + + /** + * 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() { if (!this.isValid) return this; - var vals = this.toObject(); + const vals = this.toObject(); normalizeValues(this.matrix, vals); - return clone$1(this, { - values: vals - }, true); - }; - _proto.rescale = function rescale() { + 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() { if (!this.isValid) return this; - 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]; - } + 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) { if (!this.isValid) return this; + if (units.length === 0) { return this; } - 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]; + + units = units.map((u) => Duration.normalizeUnit(u)); + + const built = {}, + accumulated = {}, + vals = this.toObject(); + let lastUnit; + + for (const k of orderedUnits$1) { if (units.indexOf(k) >= 0) { lastUnit = k; - var own = 0; - for (var ak in accumulated) { + + let own = 0; + + // anything we haven't boiled down yet should get boiled to this unit + for (const 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]; } - var i = Math.trunc(own); + + // 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); 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]; } } - for (var key in accumulated) { + + // anything leftover becomes the decimal for the last unit + // lastUnit must be defined since units is not empty + for (const 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); - }; - _proto.shiftToAll = function shiftToAll() { + 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() { if (!this.isValid) return this; - return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"); - }; - _proto.negate = function negate() { + 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() { if (!this.isValid) return this; - var negated = {}; - for (var _i5 = 0, _Object$keys2 = Object.keys(this.values); _i5 < _Object$keys2.length; _i5++) { - var k = _Object$keys2[_i5]; + const negated = {}; + for (const k of Object.keys(this.values)) { negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; } - return clone$1(this, { - values: negated - }, true); - }; - _proto.equals = function equals(other) { + 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) { 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 (var _i6 = 0, _orderedUnits3 = orderedUnits$1; _i6 < _orderedUnits3.length; _i6++) { - var u = _orderedUnits3[_i6]; + + for (const u of orderedUnits$1) { if (!eq(this.values[u], other.values[u])) { return false; } } return true; - }; - _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"; + } + } + + const INVALID$1 = "Invalid Interval"; + + // checks if the start is equal to or before the end 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; } } - var Interval = (function (_Symbol$for) { - function Interval(config) { + + /** + * 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 + */ this.s = config.start; + /** + * @access private + */ this.e = config.end; + /** + * @access private + */ this.invalid = config.invalid || null; + /** + * @access private + */ this.isLuxonInterval = true; } - Interval.invalid = function invalid(reason, explanation) { - if (explanation === void 0) { - explanation = null; - } + + /** + * 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) { if (!reason) { throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); } - var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { throw new InvalidIntervalError(invalid); } else { - return new Interval({ - invalid: invalid - }); + return new Interval({ invalid }); } - }; - Interval.fromDateTimes = function fromDateTimes(start, end) { - var builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); - var validateError = validateStartEnd(builtStart, builtEnd); + } + + /** + * 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); + if (validateError == null) { return new Interval({ start: builtStart, - end: builtEnd + end: builtEnd, }); } else { return validateError; } - }; - Interval.after = function after(start, duration) { - var dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start); + } + + /** + * 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); return Interval.fromDateTimes(dt, dt.plus(dur)); - }; - Interval.before = function before(end, duration) { - var dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end); + } + + /** + * 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); return Interval.fromDateTimes(dt.minus(dur), dt); - }; - Interval.fromISO = function fromISO(text, opts) { - var _split = (text || "").split("/", 2), s = _split[0], e = _split[1]; + } + + /** + * 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); if (s && e) { - var start, startIsValid; + let start, startIsValid; try { start = DateTime.fromISO(s, opts); startIsValid = start.isValid; } catch (e) { startIsValid = false; } - var end, endIsValid; + + let 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) { - var dur = Duration.fromISO(e, opts); + const dur = Duration.fromISO(e, opts); if (dur.isValid) { return Interval.after(start, dur); } } else if (endIsValid) { - var _dur = Duration.fromISO(s, opts); - if (_dur.isValid) { - return Interval.before(end, _dur); + const 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"); - }; - 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"; - } + 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) { if (!this.isValid) return NaN; - var start = this.start.startOf(unit, opts); - var end; - if (opts != null && opts.useLocaleWeeks) { - end = this.end.reconfigure({ - locale: start.locale - }); + const start = this.start.startOf(unit, opts); + let end; + if (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()); - }; - _proto.hasSame = function hasSame(unit) { + } + + /** + * 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) { return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; - }; - _proto.isEmpty = function isEmpty() { + } + + /** + * Return whether this Interval has the same start and end DateTimes. + * @return {boolean} + */ + isEmpty() { return this.s.valueOf() === this.e.valueOf(); - }; - _proto.isAfter = function isAfter(dateTime) { + } + + /** + * Return whether this Interval's start is after the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isAfter(dateTime) { if (!this.isValid) return false; return this.s > dateTime; - }; - _proto.isBefore = function isBefore(dateTime) { + } + + /** + * Return whether this Interval's end is before the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isBefore(dateTime) { if (!this.isValid) return false; return this.e <= dateTime; - }; - _proto.contains = function contains(dateTime) { + } + + /** + * Return whether this Interval contains the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + contains(dateTime) { if (!this.isValid) return false; return this.s <= dateTime && this.e > dateTime; - }; - _proto.set = function set(_temp) { - var _ref = _temp === void 0 ? {} : _temp, start = _ref.start, end = _ref.end; + } + + /** + * "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 } = {}) { if (!this.isValid) return this; return Interval.fromDateTimes(start || this.s, end || this.e); - }; - _proto.splitAt = function splitAt() { - var _this = this; + } + + /** + * Split this Interval at each of the specified DateTimes + * @param {...DateTime} dateTimes - the unit of time to count. + * @return {Array} + */ + splitAt(...dateTimes) { if (!this.isValid) return []; - 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; + const sorted = dateTimes + .map(friendlyDateTime) + .filter((d) => this.contains(d)) + .sort((a, b) => a.toMillis() - b.toMillis()), + results = []; + let { s } = this, + i = 0; + while (s < this.e) { - var added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; + const added = sorted[i] || this.e, + next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; i += 1; } + return results; - }; - _proto.splitBy = function splitBy(duration) { - var dur = Duration.fromDurationLike(duration); + } + + /** + * 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); + if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { return []; } - var s = this.s, idx = 1, next; - var results = []; + + let { s } = this, + idx = 1, + next; + + const results = []; while (s < this.e) { - var added = this.start.plus(dur.mapUnits(function (x) { - return x * idx; - })); + const added = this.start.plus(dur.mapUnits((x) => x * idx)); next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; idx += 1; } + return results; - }; - _proto.divideEqually = function divideEqually(numberOfParts) { + } + + /** + * 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) { if (!this.isValid) return []; return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); - }; - _proto.overlaps = function overlaps(other) { + } + + /** + * Return whether this Interval overlaps with the specified Interval + * @param {Interval} other + * @return {boolean} + */ + overlaps(other) { return this.e > other.s && this.s < other.e; - }; - _proto.abutsStart = function abutsStart(other) { + } + + /** + * Return whether this Interval's end is adjacent to the specified Interval's start. + * @param {Interval} other + * @return {boolean} + */ + abutsStart(other) { if (!this.isValid) return false; return +this.e === +other.s; - }; - _proto.abutsEnd = function abutsEnd(other) { + } + + /** + * Return whether this Interval's start is adjacent to the specified Interval's end. + * @param {Interval} other + * @return {boolean} + */ + abutsEnd(other) { if (!this.isValid) return false; return +other.e === +this.s; - }; - _proto.engulfs = function engulfs(other) { + } + + /** + * 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) { if (!this.isValid) return false; return this.s <= other.s && this.e >= other.e; - }; - _proto.equals = function equals(other) { + } + + /** + * Return whether this Interval has the same start and end as the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + equals(other) { if (!this.isValid || !other.isValid) { return false; } + return this.s.equals(other.s) && this.e.equals(other.e); - }; - _proto.intersection = function intersection(other) { + } + + /** + * 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) { if (!this.isValid) return this; - var s = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; + const 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); } - }; - _proto.union = function union(other) { + } + + /** + * 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) { if (!this.isValid) return this; - var s = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; + const s = this.s < other.s ? this.s : other.s, + e = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s, e); - }; - 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]; + } + + /** + * 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] + ); if (final) { found.push(final); } return found; - }; - 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; + } + + /** + * 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) { 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); - }; - _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() { + } + + /** + * 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() { if (!this.isValid) return INVALID$1; - return "[" + this.s.toISO() + " – " + this.e.toISO() + ")"; - }; - _proto[_Symbol$for] = function () { + 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")]() { 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} }`; } - }; - _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) { + } + + /** + * 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) { if (!this.isValid) return INVALID$1; - return this.s.toISO(opts) + "/" + this.e.toISO(opts); - }; - _proto.toISODate = function toISODate() { + 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() { if (!this.isValid) return INVALID$1; - return this.s.toISODate() + "/" + this.e.toISODate(); - }; - _proto.toISOTime = function toISOTime(opts) { + 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) { if (!this.isValid) return INVALID$1; - 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; + 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 = " – " } = {}) { if (!this.isValid) return INVALID$1; - return "" + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat); - }; - _proto.toDuration = function toDuration(unit, opts) { + 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) { if (!this.isValid) { return Duration.invalid(this.invalidReason); } return this.e.diff(this.s, unit, opts); - }; - _proto.mapEndpoints = function mapEndpoints(mapFn) { + } + + /** + * 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) { return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); - }; - _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) { + } + } + + /** + * 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) { return IANAZone.isValidZone(zone); - }; - Info.normalizeZone = function normalizeZone$1(input) { + } + + /** + * 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) { return normalizeZone(input, Settings.defaultZone); - }; - 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; + } + + /** + * 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 } = {}) { return (locObj || Locale.create(locale)).getStartOfWeek(); - }; - 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; + } + + /** + * 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 } = {}) { return (locObj || Locale.create(locale)).getMinDaysInFirstWeek(); - }; - 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; + } + + /** + * 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 return (locObj || Locale.create(locale)).getWeekendDays().slice(); - }; - 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 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" } = {} + ) { return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); - }; - 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 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" } = {} + ) { return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); - }; - 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 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 } = {}) { return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); - }; - 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 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 } = {} + ) { return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); - }; - Info.meridiems = function meridiems(_temp8) { - var _ref8 = _temp8 === void 0 ? {} : _temp8, _ref8$locale = _ref8.locale, locale = _ref8$locale === void 0 ? null : _ref8$locale; + } + + /** + * 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 } = {}) { return Locale.create(locale).meridiems(); - }; - 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 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 } = {}) { return Locale.create(locale, null, "gregory").eras(length); - }; - Info.features = function features() { - return { - relative: hasRelative(), - localeWeek: hasLocaleWeekInfo() - }; - }; - return Info; - })(); + } + + /** + * 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() }; + } + } + function dayDiff(earlier, later) { - var utcDayStart = function utcDayStart(dt) { - return dt.toUTC(0, { - keepLocalTime: true - }).startOf("day").valueOf(); - }, ms = utcDayStart(later) - utcDayStart(earlier); + const utcDayStart = (dt) => 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) { - 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]; + 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) { 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); } @@ -3491,268 +4831,296 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } } + return [cursor, results, highWater, lowestOrder]; } - 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; - }); + + 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 + ); + if (lowerOrderUnits.length === 0) { if (highWater < later) { - var _cursor$plus; - highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[lowestOrder] = 1, _cursor$plus)); + highWater = cursor.plus({ [lowestOrder]: 1 }); } + if (highWater !== cursor) { results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); } } - var duration = Duration.fromObject(results, opts); + + const duration = Duration.fromObject(results, opts); + if (lowerOrderUnits.length > 0) { - var _Duration$fromMillis; - return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration); + return Duration.fromMillis(remainingMillis, opts) + .shiftTo(...lowerOrderUnits) + .plus(duration); } else { return duration; } } - 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 MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; + + function intUnit(regex, post = (i) => i) { + return { regex, deser: ([s]) => post(parseDigits(s)) }; } - var NBSP = String.fromCharCode(160); - var spaceOrNBSP = "[ " + NBSP + "]"; - var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); + + const NBSP = String.fromCharCode(160); + const spaceOrNBSP = `[ ${NBSP}]`; + const 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, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); + return s + .replace(/\./g, "") // ignore dots that were made optional + .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp + .toLowerCase(); } + function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), - deser: function deser(_ref2) { - var s = _ref2[0]; - return strings.findIndex(function (i) { - return stripInsensitivities(s) === stripInsensitivities(i); - }) + startIndex; - } + deser: ([s]) => + strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex, }; } } + function offset(regex, groups) { - return { - regex: regex, - deser: function deser(_ref3) { - var h = _ref3[1], m = _ref3[2]; - return signedOffset(h, m); - }, - groups: groups - }; + return { regex, deser: ([, h, m]) => signedOffset(h, m), groups }; } + function simple(regex) { - return { - regex: regex, - deser: function deser(_ref4) { - var s = _ref4[0]; - return s; - } - }; + return { regex, deser: ([s]) => s }; } + function escapeToken(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } + + /** + * @param token + * @param {Locale} loc + */ function unitForToken(token, loc) { - 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 - }; - }, 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: + 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); + } + }; + + const unit = unitate(token) || { + invalidReason: MISSING_FTP, }; - var unit = unitate(token) || ({ - invalidReason: MISSING_FTP - }); + unit.token = token; + return unit; } - var partTypeStyleToTokenVal = { + + const 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) { - var type = part.type, value = part.value; + const { type, value } = part; + if (type === "literal") { - var isSpace = (/^\s+$/).test(value); + const isSpace = /^\s+$/.test(value); return { literal: !isSpace, - val: isSpace ? " " : value + val: isSpace ? " " : value, }; } - var style = formatOpts[type]; - var actualType = type; + + 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; if (type === "hour") { if (formatOpts.hour12 != null) { actualType = formatOpts.hour12 ? "hour12" : "hour24"; @@ -3763,37 +5131,41 @@ 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"; } } - var val = partTypeStyleToTokenVal[actualType]; + let val = partTypeStyleToTokenVal[actualType]; if (typeof val === "object") { val = val[style]; } + if (val) { return { literal: false, - val: val + val, }; } + return undefined; } + function buildRegex(units) { - var re = units.map(function (u) { - return u.regex; - }).reduce(function (f, r) { - return f + "(" + r.source + ")"; - }, ""); - return ["^" + re + "$", units]; + const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); + return [`^${re}$`, units]; } + function match(input, regex, handlers) { - var matches = input.match(regex); + const matches = input.match(regex); + if (matches) { - var all = {}; - var matchIndex = 1; - for (var i in handlers) { + const all = {}; + let matchIndex = 1; + for (const i in handlers) { if (hasOwnProperty(handlers, i)) { - var h = handlers[i], groups = h.groups ? h.groups + 1 : 1; + const 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)); } @@ -3805,8 +5177,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return [matches, {}]; } } + function dateTimeFromMatches(matches) { - var toField = function toField(token) { + const toField = (token) => { switch (token) { case "S": return "millisecond"; @@ -3839,20 +5212,24 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return null; } }; - var zone = null; - var specificOffset; + + let zone = null; + let 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; @@ -3860,166 +5237,211 @@ 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); } - var vals = Object.keys(matches).reduce(function (r, k) { - var f = toField(k); + + const vals = Object.keys(matches).reduce((r, k) => { + const f = toField(k); if (f) { r[f] = matches[k]; } + return r; }, {}); + return [vals, zone, specificOffset]; } - var dummyDateTimeCache = null; + + let dummyDateTimeCache = null; + function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } + return dummyDateTimeCache; } + function maybeExpandMacroToken(token, locale) { if (token.literal) { return token; } - var formatOpts = Formatter.macroTokenToFormatOpts(token.val); - var tokens = formatOptsToTokens(formatOpts, locale); + + const formatOpts = Formatter.macroTokenToFormatOpts(token.val); + const tokens = formatOptsToTokens(formatOpts, locale); + if (tokens == null || tokens.includes(undefined)) { return token; } + return tokens; } + function expandMacroTokens(tokens, locale) { - var _Array$prototype; - return (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, tokens.map(function (t) { - return maybeExpandMacroToken(t, locale); - })); + return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale))); } - var TokenParser = (function () { - function TokenParser(locale, format) { + + /** + * @private + */ + + class TokenParser { + constructor(locale, format) { this.locale = locale; this.format = format; this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale); - this.units = this.tokens.map(function (t) { - return unitForToken(t, locale); - }); - this.disqualifyingUnit = this.units.find(function (t) { - return t.invalidReason; - }); + this.units = this.tokens.map((t) => unitForToken(t, locale)); + this.disqualifyingUnit = this.units.find((t) => t.invalidReason); + if (!this.disqualifyingUnit) { - var _buildRegex = buildRegex(this.units), regexString = _buildRegex[0], handlers = _buildRegex[1]; + const [regexString, handlers] = buildRegex(this.units); this.regex = RegExp(regexString, "i"); this.handlers = handlers; } } - var _proto = TokenParser.prototype; - _proto.explainFromTokens = function explainFromTokens(input) { + + explainFromTokens(input) { if (!this.isValid) { - return { - input: input, - tokens: this.tokens, - invalidReason: this.invalidReason - }; + return { input, tokens: this.tokens, invalidReason: this.invalidReason }; } else { - 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]; + const [rawMatches, matches] = match(input, this.regex, this.handlers), + [result, zone, specificOffset] = matches + ? dateTimeFromMatches(matches) + : [null, null, undefined]; 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: rawMatches, - matches: matches, - result: result, - zone: zone, - specificOffset: specificOffset + rawMatches, + matches, + result, + zone, + specificOffset, }; } - }; - _createClass(TokenParser, [{ - key: "isValid", - get: function get() { - return !this.disqualifyingUnit; - } - }, { - key: "invalidReason", - get: function get() { - return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; - } - }]); - return TokenParser; - })(); + } + + get isValid() { + return !this.disqualifyingUnit; + } + + get invalidReason() { + return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; + } + } + function explainFromTokens(locale, input, format) { - var parser = new TokenParser(locale, format); + const parser = new TokenParser(locale, format); return parser.explainFromTokens(input); } + function parseFromTokens(locale, input, format) { - var _explainFromTokens = explainFromTokens(locale, input, format), result = _explainFromTokens.result, zone = _explainFromTokens.zone, specificOffset = _explainFromTokens.specificOffset, invalidReason = _explainFromTokens.invalidReason; + const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); return [result, zone, specificOffset, invalidReason]; } + function formatOptsToTokens(formatOpts, locale) { if (!formatOpts) { return null; } - 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 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 INVALID = "Invalid DateTime"; - var MAX_DATE = 8640000000000000; + + const INVALID = "Invalid DateTime"; + const MAX_DATE = 8.64e15; + 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) { - var current = { + const 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(_extends({}, current, alts, { - old: current - })); + return new DateTime({ ...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) { - var utcGuess = localTS - o * 60 * 1000; - var o2 = tz.offset(utcGuess); + // 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 if (o === o2) { return [utcGuess, o]; } + + // If not, change the ts by the difference in the offset utcGuess -= (o2 - o) * 60 * 1000; - var o3 = tz.offset(utcGuess); + + // If that gives us the local time we want, we're done + const 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; - var d = new Date(ts); + + const d = new Date(ts); + return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, @@ -4027,64 +5449,89 @@ 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) { - 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]; + 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); + 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: ts, - o: o - }; + + return { ts, 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) { - 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 - })); + const { setZone, zone } = opts; + if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) { + const interpretationZone = parsedZone || zone, + inst = DateTime.fromObject(parsed, { + ...opts, + zone: interpretationZone, + 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}`) + ); } } - 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; + + // 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 _toISODate(o, extended) { - var longFormat = o.c.year > 9999 || o.c.year < 0; - var c = ""; + + function toISODate(o, extended) { + const longFormat = o.c.year > 9999 || o.c.year < 0; + let c = ""; if (longFormat && o.c.year >= 0) c += "+"; c += padStart(o.c.year, longFormat ? 6 : 4); + if (extended) { c += "-"; c += padStart(o.c.month); @@ -4096,8 +5543,16 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return c; } - function _toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { - var c = padStart(o.c.hour); + + function toISOTime( + o, + extended, + suppressSeconds, + suppressMilliseconds, + includeOffset, + extendedZone + ) { + let c = padStart(o.c.hour); if (extended) { c += ":"; c += padStart(o.c.minute); @@ -4107,13 +5562,16 @@ 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"; @@ -4129,35 +5587,54 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; c += padStart(Math.trunc(o.o % 60)); } } + if (extendedZone) { c += "[" + o.zone.ianaName + "]"; } return c; } - 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"]; + + // 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 function normalizeUnit(unit) { - var normalized = ({ + const normalized = { year: "year", years: "year", month: "month", @@ -4181,11 +5658,14 @@ 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": @@ -4201,75 +5681,105 @@ 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) { - var zone = normalizeZone(opts.zone, Settings.defaultZone); + const zone = normalizeZone(opts.zone, Settings.defaultZone); if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } - var loc = Locale.fromObject(opts); - var ts, o; + + const loc = Locale.fromObject(opts); + + let ts, o; + + // assume we have the higher-order units if (!isUndefined(obj.year)) { - for (var _i = 0, _orderedUnits = orderedUnits; _i < _orderedUnits.length; _i++) { - var u = _orderedUnits[_i]; + for (const u of orderedUnits) { if (isUndefined(obj[u])) { obj[u] = defaultUnitValues[u]; } } - var invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); + + const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalid) { return DateTime.invalid(invalid); } - var offsetProvis = guessOffsetForZone(zone); - var _objToTS = objToTS(obj, offsetProvis, zone); - ts = _objToTS[0]; - o = _objToTS[1]; + + const offsetProvis = guessOffsetForZone(zone); + [ts, o] = objToTS(obj, offsetProvis, zone); } else { ts = Settings.now(); } - return new DateTime({ - ts: ts, - zone: zone, - loc: loc, - o: o - }); + + return new DateTime({ ts, zone, loc, o }); } + function diffRelative(start, end, opts) { - 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); - } - }; + 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); + } + }; + if (opts.unit) { return format(differ(opts.unit), opts.unit); } - for (var _iterator = _createForOfIteratorHelperLoose(opts.units), _step; !(_step = _iterator()).done; ) { - var unit = _step.value; - var count = differ(unit); + + for (const unit of opts.units) { + const 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) { - var opts = {}, args; + let 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); @@ -4278,134 +5788,332 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return [opts, args]; } - 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); + + /** + * 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 + */ this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; - var c = null, o = null; + + let c = null, + o = null; if (!invalid) { - var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + if (unchanged) { - var _ref = [config.old.c, config.old.o]; - c = _ref[0]; - o = _ref[1]; + [c, o] = [config.old.c, config.old.o]; } else { - var ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts); + // 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); 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; } - DateTime.now = function now() { + + // 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() { return new DateTime({}); - }; - 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]; + } + + /** + * 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; + opts.zone = FixedOffsetZone.utcInstance; - 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; + 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; if (Number.isNaN(ts)) { return DateTime.invalid("invalid input"); } - var zoneToUse = normalizeZone(options.zone, Settings.defaultZone); + + const 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), }); - }; - DateTime.fromMillis = function fromMillis(milliseconds, options) { - if (options === void 0) { - 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 = {}) { 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), }); } - }; - DateTime.fromSeconds = function fromSeconds(seconds, options) { - if (options === void 0) { - 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 = {}) { 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), }); } - }; - DateTime.fromObject = function fromObject(obj, opts) { - if (opts === void 0) { - opts = {}; - } - obj = obj || ({}); - var zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); + } + + /** + * 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); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } - 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; + + 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 + 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"); } - var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; - var units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); + + const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor); + + // configure ourselves to deal with gregorian dates or week stuff + let units, + defaultValues, + objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; @@ -4418,10 +6126,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; units = orderedUnits; defaultValues = defaultUnitValues; } - var foundFirst = false; - for (var _iterator2 = _createForOfIteratorHelperLoose(units), _step2; !(_step2 = _iterator2()).done; ) { - var u = _step2.value; - var v = normalized[u]; + + // set default values for missing stuff + let foundFirst = false; + for (const u of units) { + const v = normalized[u]; if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { @@ -4430,271 +6139,887 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; normalized[u] = objNow[u]; } } - var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); + + // 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); + if (invalid) { return DateTime.invalid(invalid); } - 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 - }); + + // 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 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; - }; - DateTime.fromISO = function fromISO(text, opts) { - if (opts === void 0) { - opts = {}; - } - var _parseISODate = parseISODate(text), vals = _parseISODate[0], parsedZone = _parseISODate[1]; + } + + /** + * 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); return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); - }; - DateTime.fromRFC2822 = function fromRFC2822(text, opts) { - if (opts === void 0) { - opts = {}; - } - var _parseRFC2822Date = parseRFC2822Date(text), vals = _parseRFC2822Date[0], parsedZone = _parseRFC2822Date[1]; + } + + /** + * 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); return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); - }; - DateTime.fromHTTP = function fromHTTP(text, opts) { - if (opts === void 0) { - opts = {}; - } - var _parseHTTPDate = parseHTTPDate(text), vals = _parseHTTPDate[0], parsedZone = _parseHTTPDate[1]; + } + + /** + * 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); return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); - }; - DateTime.fromFormat = function fromFormat(text, fmt, opts) { - if (opts === void 0) { - 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 = {}) { if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } - 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]; + + const { locale = null, numberingSystem = null } = opts, + localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true, + }), + [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt); if (invalid) { return DateTime.invalid(invalid); } else { - return parseDataToDateTime(vals, parsedZone, opts, "format " + fmt, text, specificOffset); - } - }; - DateTime.fromString = function fromString(text, fmt, opts) { - if (opts === void 0) { - opts = {}; + return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); } + } + + /** + * @deprecated use fromFormat instead + */ + static fromString(text, fmt, opts = {}) { return DateTime.fromFormat(text, fmt, opts); - }; - DateTime.fromSQL = function fromSQL(text, opts) { - if (opts === void 0) { - opts = {}; - } - var _parseSQL = parseSQL(text), vals = _parseSQL[0], parsedZone = _parseSQL[1]; + } + + /** + * 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); return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); - }; - DateTime.invalid = function invalid(reason, explanation) { - if (explanation === void 0) { - explanation = null; - } + } + + /** + * 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) { if (!reason) { throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); } - var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { throw new InvalidDateTimeError(invalid); } else { - return new DateTime({ - invalid: invalid - }); + return new DateTime({ invalid }); } - }; - 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() { + } + + /** + * 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() { zoneOffsetTs = undefined; zoneOffsetGuessCache = {}; - }; - var _proto = DateTime.prototype; - _proto.get = function get(unit) { + } + + // 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) { return this[unit]; - }; - _proto.getPossibleOffsets = function getPossibleOffsets() { - if (!this.isValid || this.isOffsetFixed) { - return [this]; - } - 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]; - } - 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]; - }; - _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); - }; - _proto.toLocal = function toLocal() { - return this.setZone(Settings.defaultZone); - }; - _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 { - var newTS = this.ts; - if (keepLocalTime || keepCalendarTime) { - 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: zone - }); - } - }; - _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; - 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"); - } - if (containsGregorMD && containsOrdinal) { - throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); - } - var mixed; - if (settingWeekStuff) { - mixed = weekToGregorian(_extends({}, gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), normalized), minDaysInFirstWeek, startOfWeek); - } else if (!isUndefined(normalized.ordinal)) { - mixed = ordinalToGregorian(_extends({}, gregorianToOrdinal(this.c), normalized)); - } else { - mixed = _extends({}, this.toObject(), normalized); - if (isUndefined(normalized.day)) { - mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); - } - } - 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; - var dur = Duration.fromDurationLike(duration); + } + + /** + * 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() { + 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); + 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 })]; + } + 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 = {}) { + 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() { + 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 } = {}) { + 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; + if (keepLocalTime || keepCalendarTime) { + const offsetGuess = zone.offset(this.ts); + const asObj = this.toObject(); + [newTS] = objToTS(asObj, offsetGuess, zone); + } + return clone(this, { ts: newTS, 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) { + 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; + + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + 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; + if (settingWeekStuff) { + mixed = weekToGregorian( + { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized }, + minDaysInFirstWeek, + startOfWeek + ); + } else if (!isUndefined(normalized.ordinal)) { + mixed = ordinalToGregorian({ ...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 + 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) { + if (!this.isValid) return this; + const dur = Duration.fromDurationLike(duration); return clone(this, adjustTime(this, dur)); - }; - _proto.minus = function minus(duration) { + } + + /** + * 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) { if (!this.isValid) return this; - var dur = Duration.fromDurationLike(duration).negate(); + const dur = Duration.fromDurationLike(duration).negate(); return clone(this, adjustTime(this, dur)); - }; - _proto.startOf = function startOf(unit, _temp3) { - var _ref4 = _temp3 === void 0 ? {} : _temp3, _ref4$useLocaleWeeks = _ref4.useLocaleWeeks, useLocaleWeeks = _ref4$useLocaleWeeks === void 0 ? false : _ref4$useLocaleWeeks; + } + + /** + * "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 } = {}) { if (!this.isValid) return this; - var o = {}, normalizedUnit = Duration.normalizeUnit(unit); + + const 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) { - var startOfWeek = this.loc.getStartOfWeek(); - var weekday = this.weekday; + const startOfWeek = this.loc.getStartOfWeek(); + const { weekday } = this; if (weekday < startOfWeek) { o.weekNumber = this.weekNumber - 1; } @@ -4703,81 +7028,247 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; o.weekday = 1; } } + if (normalizedUnit === "quarters") { - var q = Math.ceil(this.month / 3); + const q = Math.ceil(this.month / 3); o.month = (q - 1) * 3 + 1; } + return this.set(o); - }; - _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; + } + + /** + * "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, + } = {}) { if (!this.isValid) { return null; } - var ext = format === "extended"; - var c = _toISODate(this, ext); + + const ext = format === "extended"; + + let c = toISODate(this, ext); c += "T"; - c += _toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); + c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); return c; - }; - _proto.toISODate = function toISODate(_temp5) { - var _ref6 = _temp5 === void 0 ? {} : _temp5, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? "extended" : _ref6$format; + } + + /** + * 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" } = {}) { if (!this.isValid) { return null; } - return _toISODate(this, format === "extended"); - }; - _proto.toISOWeekDate = function toISOWeekDate() { + + 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 toTechFormat(this, "kkkk-'W'WW-c"); - }; - _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; + } + + /** + * 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", + } = {}) { if (!this.isValid) { return null; } - var c = includePrefix ? "T" : ""; - return c + _toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); - }; - _proto.toRFC2822 = function toRFC2822() { + + 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() { return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); - }; - _proto.toHTTP = function toHTTP() { + } + + /** + * 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() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); - }; - _proto.toSQLDate = function toSQLDate() { + } + + /** + * 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() { if (!this.isValid) { return null; } - 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"; + 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"; + if (includeZone || includeOffset) { if (includeOffsetSpace) { fmt += " "; @@ -4788,540 +7279,578 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; fmt += "ZZ"; } } + return toTechFormat(this, fmt, true); - }; - _proto.toSQL = function toSQL(opts) { - if (opts === void 0) { - opts = {}; - } + } + + /** + * 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 = {}) { if (!this.isValid) { return null; } - return this.toSQLDate() + " " + this.toSQLTime(opts); - }; - _proto.toString = function toString() { + + return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; + } + + /** + * Returns a string representation of this DateTime appropriate for debugging + * @return {string} + */ + toString() { return this.isValid ? this.toISO() : INVALID; - }; - _proto[_Symbol$for] = function () { + } + + /** + * Returns a string representation of this DateTime appropriate for the REPL. + * @return {string} + */ + [Symbol.for("nodejs.util.inspect.custom")]() { 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} }`; } - }; - _proto.valueOf = function valueOf() { + } + + /** + * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis} + * @return {number} + */ + valueOf() { return this.toMillis(); - }; - _proto.toMillis = function toMillis() { + } + + /** + * Returns the epoch milliseconds of this DateTime. + * @return {number} + */ + toMillis() { return this.isValid ? this.ts : NaN; - }; - _proto.toSeconds = function toSeconds() { + } + + /** + * Returns the epoch seconds of this DateTime. + * @return {number} + */ + toSeconds() { return this.isValid ? this.ts / 1000 : NaN; - }; - _proto.toUnixInteger = function toUnixInteger() { + } + + /** + * Returns the epoch seconds (as a whole number) of this DateTime. + * @return {number} + */ + toUnixInteger() { return this.isValid ? Math.floor(this.ts / 1000) : NaN; - }; - _proto.toJSON = function toJSON() { + } + + /** + * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. + * @return {string} + */ + toJSON() { return this.toISO(); - }; - _proto.toBSON = function toBSON() { + } + + /** + * Returns a BSON serializable equivalent to this DateTime. + * @return {Date} + */ + toBSON() { return this.toJSDate(); - }; - _proto.toObject = function toObject(opts) { - if (opts === void 0) { - opts = {}; - } + } + + /** + * 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 = {}) { if (!this.isValid) return {}; - var base = _extends({}, this.c); + + const base = { ...this.c }; + if (opts.includeConfig) { base.outputCalendar = this.outputCalendar; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; - }; - _proto.toJSDate = function toJSDate() { + } + + /** + * Returns a JavaScript Date equivalent to this DateTime. + * @return {Date} + */ + toJSDate() { return new Date(this.isValid ? this.ts : NaN); - }; - _proto.diff = function diff(otherDateTime, unit, opts) { - if (unit === void 0) { - unit = "milliseconds"; - } - if (opts === void 0) { - opts = {}; - } + } + + // 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 = {}) { if (!this.isValid || !otherDateTime.isValid) { return Duration.invalid("created by diffing an invalid DateTime"); } - 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); + + 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); + return otherIsLater ? diffed.negate() : diffed; - }; - _proto.diffNow = function diffNow(unit, opts) { - if (unit === void 0) { - unit = "milliseconds"; - } - if (opts === void 0) { - opts = {}; - } + } + + /** + * 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 = {}) { return this.diff(DateTime.now(), unit, opts); - }; - _proto.until = function until(otherDateTime) { + } + + /** + * Return an Interval spanning between this DateTime and another DateTime + * @param {DateTime} otherDateTime - the other end point of the Interval + * @return {Interval} + */ + until(otherDateTime) { return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; - }; - _proto.hasSame = function hasSame(otherDateTime, unit, opts) { + } + + /** + * 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) { if (!this.isValid) return false; - 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 = {}; - } + + 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 = {}) { if (!this.isValid) return null; - 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; + 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; if (Array.isArray(options.unit)) { units = options.unit; unit = undefined; } - return diffRelative(base, this.plus(padding), _extends({}, options, { + return diffRelative(base, this.plus(padding), { + ...options, numeric: "always", - units: units, - unit: unit - })); - }; - _proto.toRelativeCalendar = function toRelativeCalendar(options) { - if (options === void 0) { - options = {}; - } + 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 = {}) { if (!this.isValid) return null; - return diffRelative(options.base || DateTime.fromObject({}, { - zone: this.zone - }), this, _extends({}, options, { + + return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, { + ...options, numeric: "auto", units: ["years", "months", "days"], - calendary: true - })); - }; - DateTime.min = function min() { - for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { - dateTimes[_key] = arguments[_key]; - } + 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) { if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("min requires all arguments be 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]; - } + 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) { if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } - 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 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 explainFromTokens(localeToUse, text, fmt); - }; - DateTime.fromStringExplain = function fromStringExplain(text, fmt, options) { - if (options === void 0) { - options = {}; - } + } + + /** + * @deprecated use fromFormatExplain instead + */ + static fromStringExplain(text, fmt, options = {}) { return DateTime.fromFormatExplain(text, fmt, options); - }; - 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 - }); + } + + /** + * 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, + }); return new TokenParser(localeToUse, fmt); - }; - DateTime.fromFormatParser = function fromFormatParser(text, formatParser, opts) { - if (opts === void 0) { - opts = {}; - } + } + + /** + * 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 = {}) { if (isUndefined(text) || isUndefined(formatParser)) { - 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 - }); + 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, + }); + 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}` + ); } - var _formatParser$explain = formatParser.explainFromTokens(text), result = _formatParser$explain.result, zone = _formatParser$explain.zone, specificOffset = _formatParser$explain.specificOffset, invalidReason = _formatParser$explain.invalidReason; + + const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text); + if (invalidReason) { return DateTime.invalid(invalidReason); } else { - return parseDataToDateTime(result, zone, opts, "format " + formatParser.format, text, specificOffset); - } - }; - _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; - } + return parseDataToDateTime( + result, + zone, + opts, + `format ${formatParser.format}`, + text, + specificOffset + ); } - }, { - 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")); + } + + // 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 + */ function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; @@ -5330,37 +7859,27 @@ 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); - } - } - 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; - - try { Object.defineProperty(luxon, "__" + "esModule", { value: true }); luxon.default = luxon; } 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 = luxon; - - Object.defineProperty(exports, '__esModule', { value: true }); + 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; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/3735c14e/cmis.js b/packages/ui5-tooling-modules/test/__snap__/3735c14e/cmis.js index aa1872ec3..575f63cb5 100644 --- a/packages/ui5-tooling-modules/test/__snap__/3735c14e/cmis.js +++ b/packages/ui5-tooling-modules/test/__snap__/3735c14e/cmis.js @@ -2,475 +2,19834 @@ sap.ui.define((function () { 'use strict'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + 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 cmis$1 = {}; - var cmis = {}; + var cmis = {}; + + var browser$3 = {exports: {}}; + + (function (module, exports) { + + // ref: https://github.com/tc39/proposal-global + var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof commonjsGlobal !== 'undefined') { return commonjsGlobal; } + throw new Error('unable to locate global object'); + }; + + var globalObject = getGlobal(); + + module.exports = exports = globalObject.fetch; + + // Needed for TypeScript and Webpack. + if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); + } + + exports.Headers = globalObject.Headers; + exports.Request = globalObject.Request; + exports.Response = globalObject.Response; + } (browser$3, browser$3.exports)); + + var browserExports = browser$3.exports; + + var realFetch = browserExports; + + var fetch$2 = function (url, options) { + // Support schemaless URIs on the server for parity with the browser. + // Ex: //github.com/ -> https://github.com/ + if (/^\/\//.test(url)) { + url = 'https:' + url; + } + return realFetch.call(this, url, options); + }; + + fetch$2.fetch = fetch$2; + fetch$2.Response = realFetch.Response, + fetch$2.Headers = realFetch.Headers, + fetch$2.Request = realFetch.Request, + fetch$2.polyfill = false; + + var node = fetch$2; + + var fetchNode = node; + var fetch$1 = fetchNode.fetch.bind({}); + + fetch$1.polyfill = true; + + if (!commonjsGlobal.fetch) { + commonjsGlobal.fetch = fetch$1; + commonjsGlobal.Response = fetchNode.Response; + commonjsGlobal.Headers = fetchNode.Headers; + commonjsGlobal.Request = fetchNode.Request; + } + + var browser$2 = {}; + + browser$2.atob = self.atob.bind(self); + browser$2.btoa = self.btoa.bind(self); + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + 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; + } + + function toByteArray(b64) { + if (!inited) { + init(); + } + 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"); + } + + // 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 = 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); + } + + // 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; + } + } + 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 (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + 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); + } + + 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); + } + return that; + } + + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that; + } + + obj.copy(that, 0, 0, len); + return that; + } + + 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 (obj.type === "Buffer" && isArray$2(obj.data)) { + return fromArrayLike(that, obj.data); + } + } + + 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$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); + + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + + // 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; + } + + 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"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + 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"); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + 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"); + } + 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 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); + }; + + 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; + }; + + 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 ""; + }; + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); + } + + 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; + } + 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); + } + + // 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() + } + + // 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; + } + + 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); + } + 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 ret; + } + + 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; + 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 < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + 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; + }; + + /* + * 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 val; + }; + + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + 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)); + } + + // 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 = ''; // 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, + 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 + }; + + 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$1(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(global$1.process)) { + return function () { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (browser$1.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (browser$1.throwDeprecation) { + throw new Error(msg); + } else if (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 = 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$1.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$1(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$1(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$1(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$1(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$1(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(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$1(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$1.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$1(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) { + browser$1.nextTick(cb.bind(null, null, ret)); + }, + function (rej) { + 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$1, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$1, + inspect: inspect, + deprecate: deprecate, + format: format$1, + 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$1, + inherits: inherits$1, + inspect: inspect, + isArray: isArray$1, + isBoolean: isBoolean, + isBuffer: isBuffer, + isDate: isDate, + isError: isError, + isFunction: isFunction$1, + isNull: isNull, + isNullOrUndefined: isNullOrUndefined, + isNumber: isNumber, + isObject: isObject, + isPrimitive: isPrimitive, + isPromise: isPromise, + isRegExp: isRegExp, + isString: isString, + isSymbol: isSymbol, + isUndefined: isUndefined, + log: log, + promisify: promisify, + types: types + }); + + var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util); + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + // Alias for removeListener added in NodeJS 10.0 + // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener + EventEmitter.prototype.off = function(type, listener){ + return this.removeListener(type, listener); + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream$3, EventEmitter); + Stream$3.Readable = Readable; + Stream$3.Writable = Writable; + Stream$3.Duplex = Duplex; + Stream$3.Transform = Transform; + Stream$3.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream$3.Stream = Stream$3; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream$3() { + EventEmitter.call(this); + } + + Stream$3.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + var _polyfillNode_stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + Duplex: Duplex, + PassThrough: PassThrough, + Readable: Readable, + Stream: Stream$3, + Transform: Transform, + Writable: Writable, + default: Stream$3 + }); + + var require$$7 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_stream); + + var Stream$2 = require$$7.Stream; + var util$2 = require$$1; + + var delayed_stream = DelayedStream$1; + function DelayedStream$1() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; + } + util$2.inherits(DelayedStream$1, Stream$2); + + DelayedStream$1.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; + }; + + Object.defineProperty(DelayedStream$1.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } + }); + + DelayedStream$1.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); + }; + + DelayedStream$1.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); + }; + + DelayedStream$1.prototype.pause = function() { + this.source.pause(); + }; + + DelayedStream$1.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; + }; + + DelayedStream$1.prototype.pipe = function() { + var r = Stream$2.prototype.pipe.apply(this, arguments); + this.resume(); + return r; + }; + + DelayedStream$1.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); + }; + + DelayedStream$1.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this.emit('error', new Error(message)); + }; + + var util$1 = require$$1; + var Stream$1 = require$$7.Stream; + var DelayedStream = delayed_stream; + + var combined_stream = CombinedStream$1; + function CombinedStream$1() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; + } + util$1.inherits(CombinedStream$1, Stream$1); + + CombinedStream$1.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; + }; + + CombinedStream$1.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); + }; + + CombinedStream$1.prototype.append = function(stream) { + var isStreamLike = CombinedStream$1.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; + }; + + CombinedStream$1.prototype.pipe = function(dest, options) { + Stream$1.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; + }; + + CombinedStream$1.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } + }; + + CombinedStream$1.prototype._realGetNext = function() { + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream$1.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); + }; + + CombinedStream$1.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream$1.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); + }; + + CombinedStream$1.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); + }; + + CombinedStream$1.prototype.write = function(data) { + this.emit('data', data); + }; + + CombinedStream$1.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); + }; + + CombinedStream$1.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); + }; + + CombinedStream$1.prototype.end = function() { + this._reset(); + this.emit('end'); + }; + + CombinedStream$1.prototype.destroy = function() { + this._reset(); + this.emit('close'); + }; + + CombinedStream$1.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; + }; + + CombinedStream$1.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); + }; + + CombinedStream$1.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } + }; + + CombinedStream$1.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // resolves . and .. elements in a path array with directory names there + // must be no slashes, empty elements, or device names (c:\) in the array + // (so also no leading and trailing slashes - it does not distinguish + // relative and absolute paths) + function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; + } + + // Split a filename into [root, dir, basename, ext], unix version + // 'root' is just a slash, or nothing. + var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; + var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); + }; + + // path.resolve([from ...], to) + // posix version + function resolve() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : '/'; + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; + } + // path.normalize(path) + // posix version + function normalize(path) { + var isPathAbsolute = isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isPathAbsolute).join('/'); + + if (!path && !isPathAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isPathAbsolute ? '/' : '') + path; + } + // posix version + function isAbsolute(path) { + return path.charAt(0) === '/'; + } + + // posix version + function join() { + var paths = Array.prototype.slice.call(arguments, 0); + return normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); + } + + + // path.relative(from, to) + // posix version + function relative(from, to) { + from = resolve(from).substr(1); + to = resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); + } + + var sep = '/'; + var delimiter$1 = ':'; + + function dirname(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; + } + + function basename(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; + } + + + function extname(path) { + return splitPath(path)[3]; + } + var _polyfillNode_path = { + extname: extname, + basename: basename, + dirname: dirname, + sep: sep, + delimiter: delimiter$1, + relative: relative, + join: join, + isAbsolute: isAbsolute, + normalize: normalize, + resolve: resolve + }; + function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; + } + + // String.prototype.substr - negative index don't work in IE8 + var substr = 'ab'.substr(-1) === 'b' ? + function (str, start, len) { return str.substr(start, len) } : + function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } + ; + + var _polyfillNode_path$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + basename: basename, + default: _polyfillNode_path, + delimiter: delimiter$1, + dirname: dirname, + extname: extname, + isAbsolute: isAbsolute, + join: join, + normalize: normalize, + relative: relative, + resolve: resolve, + sep: sep + }); + + var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path$1); + + var hasFetch = isFunction(global$1.fetch) && isFunction(global$1.ReadableStream); + + var _blobConstructor; + function blobConstructor() { + if (typeof _blobConstructor !== 'undefined') { + return _blobConstructor; + } + try { + new global$1.Blob([new ArrayBuffer(1)]); + _blobConstructor = true; + } catch (e) { + _blobConstructor = false; + } + return _blobConstructor + } + var xhr; + + function checkTypeSupport(type) { + if (!xhr) { + xhr = new global$1.XMLHttpRequest(); + // If location.host is empty, e.g. if this page/worker was loaded + // from a Blob, then use example.com to avoid an error + xhr.open('GET', global$1.location.host ? '/' : 'https://example.com'); + } + try { + xhr.responseType = type; + return xhr.responseType === type + } catch (e) { + return false + } + + } + + // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. + // Safari 7.1 appears to have fixed this bug. + var haveArrayBuffer = typeof global$1.ArrayBuffer !== 'undefined'; + var haveSlice = haveArrayBuffer && isFunction(global$1.ArrayBuffer.prototype.slice); + + var arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer'); + // These next two tests unavoidably show warnings in Chrome. Since fetch will always + // be used if it's available, just return false for these to avoid the warnings. + var msstream = !hasFetch && haveSlice && checkTypeSupport('ms-stream'); + var mozchunkedarraybuffer = !hasFetch && haveArrayBuffer && + checkTypeSupport('moz-chunked-arraybuffer'); + var overrideMimeType = isFunction(xhr.overrideMimeType); + var vbArray = isFunction(global$1.VBArray); + + function isFunction(value) { + return typeof value === 'function' + } + + xhr = null; // Help gc + + var rStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 + }; + function IncomingMessage(xhr, response, mode) { + var self = this; + Readable.call(self); + + self._mode = mode; + self.headers = {}; + self.rawHeaders = []; + self.trailers = {}; + self.rawTrailers = []; + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function() { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + browser$1.nextTick(function() { + self.emit('close'); + }); + }); + var read; + if (mode === 'fetch') { + self._fetchResponse = response; + + self.url = response.url; + self.statusCode = response.status; + self.statusMessage = response.statusText; + // backwards compatible version of for ( of ): + // for (var ,_i,_it = [Symbol.iterator](); = (_i = _it.next()).value,!_i.done;) + for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) { + self.headers[header[0].toLowerCase()] = header[1]; + self.rawHeaders.push(header[0], header[1]); + } + + // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed + var reader = response.body.getReader(); + + read = function () { + reader.read().then(function(result) { + if (self._destroyed) + return + if (result.done) { + self.push(null); + return + } + self.push(new Buffer(result.value)); + read(); + }); + }; + read(); + + } else { + self._xhr = xhr; + self._pos = 0; + + self.url = xhr.responseURL; + self.statusCode = xhr.status; + self.statusMessage = xhr.statusText; + var headers = xhr.getAllResponseHeaders().split(/\r?\n/); + headers.forEach(function(header) { + var matches = header.match(/^([^:]+):\s*(.*)/); + if (matches) { + var key = matches[1].toLowerCase(); + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = []; + } + self.headers[key].push(matches[2]); + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2]; + } else { + self.headers[key] = matches[2]; + } + self.rawHeaders.push(matches[1], matches[2]); + } + }); + + self._charset = 'x-user-defined'; + if (!overrideMimeType) { + var mimeType = self.rawHeaders['mime-type']; + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/); + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase(); + } + } + if (!self._charset) + self._charset = 'utf-8'; // best guess + } + } + } + + inherits$1(IncomingMessage, Readable); + + IncomingMessage.prototype._read = function() {}; + + IncomingMessage.prototype._onXHRProgress = function() { + var self = this; + + var xhr = self._xhr; + + var response = null; + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global$1.VBArray(xhr.responseBody).toArray(); + } catch (e) { + // pass + } + if (response !== null) { + self.push(new Buffer(response)); + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText; + } catch (e) { + self._mode = 'text:vbarray'; + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos); + if (self._charset === 'x-user-defined') { + var buffer = new Buffer(newData.length); + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff; + + self.push(buffer); + } else { + self.push(newData, self._charset); + } + self._pos = response.length; + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response; + self.push(new Buffer(new Uint8Array(response))); + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response; + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))); + break + case 'ms-stream': + response = xhr.response; + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global$1.MSStreamReader(); + reader.onprogress = function() { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))); + self._pos = reader.result.byteLength; + } + }; + reader.onload = function() { + self.push(null); + }; + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response); + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null); + } + }; + + // from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js + + function toArrayBuffer (buf) { + // If the buffer is backed by a Uint8Array, a faster version will work + if (buf instanceof Uint8Array) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) + } + } + + if (isBuffer$1(buf)) { + // This is the slow version that will work with any Buffer + // implementation (even in old browsers) + var arrayCopy = new Uint8Array(buf.length); + var len = buf.length; + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i]; + } + return arrayCopy.buffer + } else { + throw new Error('Argument must be a Buffer') + } + } + + function decideMode(preferBinary, useFetch) { + if (hasFetch && useFetch) { + return 'fetch' + } else if (mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (msstream) { + return 'ms-stream' + } else if (arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } + } + + function ClientRequest(opts) { + var self = this; + Writable.call(self); + + self._opts = opts; + self._body = []; + self._headers = {}; + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')); + Object.keys(opts.headers).forEach(function(name) { + self.setHeader(name, opts.headers[name]); + }); + + var preferBinary; + var useFetch = true; + if (opts.mode === 'disable-fetch') { + // If the use of XHR should be preferred and includes preserving the 'content-type' header + useFetch = false; + preferBinary = true; + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false; + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !overrideMimeType; + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true; + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch); + + self.on('finish', function() { + self._onFinish(); + }); + } + + inherits$1(ClientRequest, Writable); + // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method + var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'user-agent', + 'via' + ]; + ClientRequest.prototype.setHeader = function(name, value) { + var self = this; + var lowerName = name.toLowerCase(); + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + }; + }; + + ClientRequest.prototype.getHeader = function(name) { + var self = this; + return self._headers[name.toLowerCase()].value + }; + + ClientRequest.prototype.removeHeader = function(name) { + var self = this; + delete self._headers[name.toLowerCase()]; + }; + + ClientRequest.prototype._onFinish = function() { + var self = this; + + if (self._destroyed) + return + var opts = self._opts; + + var headersObj = self._headers; + var body; + if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { + if (blobConstructor()) { + body = new global$1.Blob(self._body.map(function(buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }); + } else { + // get utf8 string + body = Buffer.concat(self._body).toString(); + } + } + + if (self._mode === 'fetch') { + var headers = Object.keys(headersObj).map(function(name) { + return [headersObj[name].name, headersObj[name].value] + }); + + global$1.fetch(self._opts.url, { + method: self._opts.method, + headers: headers, + body: body, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin' + }).then(function(response) { + self._fetchResponse = response; + self._connect(); + }, function(reason) { + self.emit('error', reason); + }); + } else { + var xhr = self._xhr = new global$1.XMLHttpRequest(); + try { + xhr.open(self._opts.method, self._opts.url, true); + } catch (err) { + browser$1.nextTick(function() { + self.emit('error', err); + }); + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0]; + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials; + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined'); + + Object.keys(headersObj).forEach(function(name) { + xhr.setRequestHeader(headersObj[name].name, headersObj[name].value); + }); + + self._response = null; + xhr.onreadystatechange = function() { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress(); + break + } + }; + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function() { + self._onXHRProgress(); + }; + } + + xhr.onerror = function() { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')); + }; + + try { + xhr.send(body); + } catch (err) { + browser$1.nextTick(function() { + self.emit('error', err); + }); + return + } + } + }; + + /** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ + function statusValid(xhr) { + try { + var status = xhr.status; + return (status !== null && status !== 0) + } catch (e) { + return false + } + } + + ClientRequest.prototype._onXHRProgress = function() { + var self = this; + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect(); + + self._response._onXHRProgress(); + }; + + ClientRequest.prototype._connect = function() { + var self = this; + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode); + self.emit('response', self._response); + }; + + ClientRequest.prototype._write = function(chunk, encoding, cb) { + var self = this; + + self._body.push(chunk); + cb(); + }; + + ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function() { + var self = this; + self._destroyed = true; + if (self._response) + self._response._destroyed = true; + if (self._xhr) + self._xhr.abort(); + // Currently, there isn't a way to truly abort a fetch. + // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 + }; + + ClientRequest.prototype.end = function(data, encoding, cb) { + var self = this; + if (typeof data === 'function') { + cb = data; + data = undefined; + } + + Writable.prototype.end.call(self, data, encoding, cb); + }; + + ClientRequest.prototype.flushHeaders = function() {}; + ClientRequest.prototype.setTimeout = function() {}; + ClientRequest.prototype.setNoDelay = function() {}; + ClientRequest.prototype.setSocketKeepAlive = function() {}; + + /*! https://mths.be/punycode v1.4.1 by @mathias */ + + + /** Highest positive signed 32-bit float value */ + var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + var base = 36; + var tMin = 1; + var tMax = 26; + var skew = 38; + var damp = 700; + var initialBias = 72; + var initialN = 128; // 0x80 + var delimiter = '-'; // '\x2D' + var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars + var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }; + + /** Convenience shortcuts */ + var baseMinusTMin = base - tMin; + var floor = Math.floor; + var stringFromCharCode = String.fromCharCode; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map$1(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map$1(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */ ; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) ? + 'xn--' + encode(string) : + string; + }); + } + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; + }; + function stringifyPrimitive(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + } + + function stringify (obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + } + function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; + } + + var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; + }; + + function parse$1(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + } + + // WHATWG API + const URL = global$1.URL; + const URLSearchParams$1 = global$1.URLSearchParams; + var _polyfillNode_url = { + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + fileURLToPath: urlFileURLToPath, + format: urlFormat, + Url: Url, + + // WHATWG API + URL, + URLSearchParams: URLSearchParams$1, + }; + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + return parse(this, url, parseQueryString, slashesDenoteHost); + }; + + function parse(self, url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + self.path = rest; + self.href = rest; + self.pathname = simplePath[1]; + if (simplePath[2]) { + self.search = simplePath[2]; + if (parseQueryString) { + self.query = parse$1(self.search.substr(1)); + } else { + self.query = self.search.substr(1); + } + } else if (parseQueryString) { + self.search = ''; + self.query = {}; + } + return self; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + self.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + self.slashes = true; + } + } + var i, hec, l, p; + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + self.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + self.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + parseHost(self); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + self.hostname = self.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = self.hostname[0] === '[' && + self.hostname[self.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = self.hostname.split(/\./); + for (i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + self.hostname = validParts.join('.'); + break; + } + } + } + } + + if (self.hostname.length > hostnameMaxLen) { + self.hostname = ''; + } else { + // hostnames are always lower case. + self.hostname = self.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + self.hostname = toASCII(self.hostname); + } + + p = self.port ? ':' + self.port : ''; + var h = self.hostname || ''; + self.host = h + p; + self.href += self.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + self.hostname = self.hostname.substr(1, self.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + self.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + self.search = rest.substr(qm); + self.query = rest.substr(qm + 1); + if (parseQueryString) { + self.query = parse$1(self.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + self.search = ''; + self.query = {}; + } + if (rest) self.pathname = rest; + if (slashedProtocol[lowerProto] && + self.hostname && !self.pathname) { + self.pathname = '/'; + } + + //to support http.request + if (self.pathname || self.search) { + p = self.pathname || ''; + var s = self.search || ''; + self.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + self.href = format(self); + return self; + } + + function urlFileURLToPath(path) { + if (typeof path === 'string') + path = new Url().parse(path); + else if (!(path instanceof Url)) + throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path)); + if (path.protocol !== 'file:') + throw new TypeError('The URL must be of scheme file'); + return getPathFromURLPosix(path); + } + + function getPathFromURLPosix(url) { + const pathname = url.pathname; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + const third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new TypeError( + 'must not include encoded / characters' + ); + } + } + } + return decodeURIComponent(pathname); + } + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString(obj)) obj = parse({}, obj); + return format(obj); + } + + function format(self) { + var auth = self.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = self.protocol || '', + pathname = self.pathname || '', + hash = self.hash || '', + host = false, + query = ''; + + if (self.host) { + host = auth + self.host; + } else if (self.hostname) { + host = auth + (self.hostname.indexOf(':') === -1 ? + self.hostname : + '[' + this.hostname + ']'); + if (self.port) { + host += ':' + self.port; + } + } + + if (self.query && + isObject(self.query) && + Object.keys(self.query).length) { + query = stringify(self.query); + } + + var search = self.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (self.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + } + + Url.prototype.format = function() { + return format(this); + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + var relPath; + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + relPath = relative.pathname && relative.pathname.split('/') || []; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + var authInHost; + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + return parseHost(this); + }; + + function parseHost(self) { + var host = self.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + self.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) self.hostname = host; + } + + var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + URL: URL, + URLSearchParams: URLSearchParams$1, + Url: Url, + default: _polyfillNode_url, + fileURLToPath: urlFileURLToPath, + format: urlFormat, + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject + }); + + function request$1(opts, cb) { + if (typeof opts === 'string') + opts = urlParse(opts); + + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global$1.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''; + + var protocol = opts.protocol || defaultProtocol; + var host = opts.hostname || opts.host; + var port = opts.port; + var path = opts.path || '/'; + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']'; + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path; + opts.method = (opts.method || 'GET').toUpperCase(); + opts.headers = opts.headers || {}; + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts); + if (cb) + req.on('response', cb); + return req + } + + function get$1(opts, cb) { + var req = request$1(opts, cb); + req.end(); + return req + } + + function Agent$1() {} + Agent$1.defaultMaxSockets = 4; + + var METHODS$1 = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' + ]; + var STATUS_CODES$1 = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200: 'OK', + 201: 'Created', + 202: 'Accepted', + 203: 'Non-Authoritative Information', + 204: 'No Content', + 205: 'Reset Content', + 206: 'Partial Content', + 207: 'Multi-Status', // RFC 4918 + 300: 'Multiple Choices', + 301: 'Moved Permanently', + 302: 'Moved Temporarily', + 303: 'See Other', + 304: 'Not Modified', + 305: 'Use Proxy', + 307: 'Temporary Redirect', + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Time-out', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Request Entity Too Large', + 414: 'Request-URI Too Large', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'I\'m a teapot', // RFC 2324 + 422: 'Unprocessable Entity', // RFC 4918 + 423: 'Locked', // RFC 4918 + 424: 'Failed Dependency', // RFC 4918 + 425: 'Unordered Collection', // RFC 4918 + 426: 'Upgrade Required', // RFC 2817 + 428: 'Precondition Required', // RFC 6585 + 429: 'Too Many Requests', // RFC 6585 + 431: 'Request Header Fields Too Large', // RFC 6585 + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Time-out', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', // RFC 2295 + 507: 'Insufficient Storage', // RFC 4918 + 509: 'Bandwidth Limit Exceeded', + 510: 'Not Extended', // RFC 2774 + 511: 'Network Authentication Required' // RFC 6585 + }; + + var _polyfillNode_http = { + request: request$1, + get: get$1, + Agent: Agent$1, + METHODS: METHODS$1, + STATUS_CODES: STATUS_CODES$1 + }; + + var _polyfillNode_http$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Agent: Agent$1, + METHODS: METHODS$1, + STATUS_CODES: STATUS_CODES$1, + default: _polyfillNode_http, + get: get$1, + request: request$1 + }); + + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_http$1); + + function request(opts, cb) { + if (typeof opts === 'string') + opts = urlParse(opts); + + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global$1.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''; + + var protocol = opts.protocol || defaultProtocol; + var host = opts.hostname || opts.host; + var port = opts.port; + var path = opts.path || '/'; + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']'; + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path; + opts.method = (opts.method || 'GET').toUpperCase(); + opts.headers = opts.headers || {}; + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts); + if (cb) + req.on('response', cb); + return req + } + + function get(opts, cb) { + var req = request(opts, cb); + req.end(); + return req + } + + function Agent() {} + Agent.defaultMaxSockets = 4; + + var METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' + ]; + var STATUS_CODES = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200: 'OK', + 201: 'Created', + 202: 'Accepted', + 203: 'Non-Authoritative Information', + 204: 'No Content', + 205: 'Reset Content', + 206: 'Partial Content', + 207: 'Multi-Status', // RFC 4918 + 300: 'Multiple Choices', + 301: 'Moved Permanently', + 302: 'Moved Temporarily', + 303: 'See Other', + 304: 'Not Modified', + 305: 'Use Proxy', + 307: 'Temporary Redirect', + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Time-out', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Request Entity Too Large', + 414: 'Request-URI Too Large', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'I\'m a teapot', // RFC 2324 + 422: 'Unprocessable Entity', // RFC 4918 + 423: 'Locked', // RFC 4918 + 424: 'Failed Dependency', // RFC 4918 + 425: 'Unordered Collection', // RFC 4918 + 426: 'Upgrade Required', // RFC 2817 + 428: 'Precondition Required', // RFC 6585 + 429: 'Too Many Requests', // RFC 6585 + 431: 'Request Header Fields Too Large', // RFC 6585 + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Time-out', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', // RFC 2295 + 507: 'Insufficient Storage', // RFC 4918 + 509: 'Bandwidth Limit Exceeded', + 510: 'Not Extended', // RFC 2774 + 511: 'Network Authentication Required' // RFC 6585 + }; + + var _polyfillNode_https = { + request, + get, + Agent, + METHODS, + STATUS_CODES + }; + + var _polyfillNode_https$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Agent: Agent, + METHODS: METHODS, + STATUS_CODES: STATUS_CODES, + default: _polyfillNode_https, + get: get, + request: request + }); + + var require$$4 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_https$1); + + var require$$5 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1); + + var _polyfillNode_fs = {}; + + var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_fs + }); + + var require$$6 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1); + + var mimeTypes = {}; + + var require$$0 = { + "application/1d-interleaved-parityfec": { + source: "iana" + }, + "application/3gpdash-qoe-report+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/3gpp-ims+xml": { + source: "iana", + compressible: true + }, + "application/3gpphal+json": { + source: "iana", + compressible: true + }, + "application/3gpphalforms+json": { + source: "iana", + compressible: true + }, + "application/a2l": { + source: "iana" + }, + "application/ace+cbor": { + source: "iana" + }, + "application/activemessage": { + source: "iana" + }, + "application/activity+json": { + source: "iana", + compressible: true + }, + "application/alto-costmap+json": { + source: "iana", + compressible: true + }, + "application/alto-costmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-directory+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcost+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcostparams+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointprop+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointpropparams+json": { + source: "iana", + compressible: true + }, + "application/alto-error+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmap+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamcontrol+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamparams+json": { + source: "iana", + compressible: true + }, + "application/aml": { + source: "iana" + }, + "application/andrew-inset": { + source: "iana", + extensions: [ + "ez" + ] + }, + "application/applefile": { + source: "iana" + }, + "application/applixware": { + source: "apache", + extensions: [ + "aw" + ] + }, + "application/at+jwt": { + source: "iana" + }, + "application/atf": { + source: "iana" + }, + "application/atfx": { + source: "iana" + }, + "application/atom+xml": { + source: "iana", + compressible: true, + extensions: [ + "atom" + ] + }, + "application/atomcat+xml": { + source: "iana", + compressible: true, + extensions: [ + "atomcat" + ] + }, + "application/atomdeleted+xml": { + source: "iana", + compressible: true, + extensions: [ + "atomdeleted" + ] + }, + "application/atomicmail": { + source: "iana" + }, + "application/atomsvc+xml": { + source: "iana", + compressible: true, + extensions: [ + "atomsvc" + ] + }, + "application/atsc-dwd+xml": { + source: "iana", + compressible: true, + extensions: [ + "dwd" + ] + }, + "application/atsc-dynamic-event-message": { + source: "iana" + }, + "application/atsc-held+xml": { + source: "iana", + compressible: true, + extensions: [ + "held" + ] + }, + "application/atsc-rdt+json": { + source: "iana", + compressible: true + }, + "application/atsc-rsat+xml": { + source: "iana", + compressible: true, + extensions: [ + "rsat" + ] + }, + "application/atxml": { + source: "iana" + }, + "application/auth-policy+xml": { + source: "iana", + compressible: true + }, + "application/bacnet-xdd+zip": { + source: "iana", + compressible: false + }, + "application/batch-smtp": { + source: "iana" + }, + "application/bdoc": { + compressible: false, + extensions: [ + "bdoc" + ] + }, + "application/beep+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/calendar+json": { + source: "iana", + compressible: true + }, + "application/calendar+xml": { + source: "iana", + compressible: true, + extensions: [ + "xcs" + ] + }, + "application/call-completion": { + source: "iana" + }, + "application/cals-1840": { + source: "iana" + }, + "application/captive+json": { + source: "iana", + compressible: true + }, + "application/cbor": { + source: "iana" + }, + "application/cbor-seq": { + source: "iana" + }, + "application/cccex": { + source: "iana" + }, + "application/ccmp+xml": { + source: "iana", + compressible: true + }, + "application/ccxml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ccxml" + ] + }, + "application/cdfx+xml": { + source: "iana", + compressible: true, + extensions: [ + "cdfx" + ] + }, + "application/cdmi-capability": { + source: "iana", + extensions: [ + "cdmia" + ] + }, + "application/cdmi-container": { + source: "iana", + extensions: [ + "cdmic" + ] + }, + "application/cdmi-domain": { + source: "iana", + extensions: [ + "cdmid" + ] + }, + "application/cdmi-object": { + source: "iana", + extensions: [ + "cdmio" + ] + }, + "application/cdmi-queue": { + source: "iana", + extensions: [ + "cdmiq" + ] + }, + "application/cdni": { + source: "iana" + }, + "application/cea": { + source: "iana" + }, + "application/cea-2018+xml": { + source: "iana", + compressible: true + }, + "application/cellml+xml": { + source: "iana", + compressible: true + }, + "application/cfw": { + source: "iana" + }, + "application/city+json": { + source: "iana", + compressible: true + }, + "application/clr": { + source: "iana" + }, + "application/clue+xml": { + source: "iana", + compressible: true + }, + "application/clue_info+xml": { + source: "iana", + compressible: true + }, + "application/cms": { + source: "iana" + }, + "application/cnrp+xml": { + source: "iana", + compressible: true + }, + "application/coap-group+json": { + source: "iana", + compressible: true + }, + "application/coap-payload": { + source: "iana" + }, + "application/commonground": { + source: "iana" + }, + "application/conference-info+xml": { + source: "iana", + compressible: true + }, + "application/cose": { + source: "iana" + }, + "application/cose-key": { + source: "iana" + }, + "application/cose-key-set": { + source: "iana" + }, + "application/cpl+xml": { + source: "iana", + compressible: true, + extensions: [ + "cpl" + ] + }, + "application/csrattrs": { + source: "iana" + }, + "application/csta+xml": { + source: "iana", + compressible: true + }, + "application/cstadata+xml": { + source: "iana", + compressible: true + }, + "application/csvm+json": { + source: "iana", + compressible: true + }, + "application/cu-seeme": { + source: "apache", + extensions: [ + "cu" + ] + }, + "application/cwt": { + source: "iana" + }, + "application/cybercash": { + source: "iana" + }, + "application/dart": { + compressible: true + }, + "application/dash+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpd" + ] + }, + "application/dash-patch+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpp" + ] + }, + "application/dashdelta": { + source: "iana" + }, + "application/davmount+xml": { + source: "iana", + compressible: true, + extensions: [ + "davmount" + ] + }, + "application/dca-rft": { + source: "iana" + }, + "application/dcd": { + source: "iana" + }, + "application/dec-dx": { + source: "iana" + }, + "application/dialog-info+xml": { + source: "iana", + compressible: true + }, + "application/dicom": { + source: "iana" + }, + "application/dicom+json": { + source: "iana", + compressible: true + }, + "application/dicom+xml": { + source: "iana", + compressible: true + }, + "application/dii": { + source: "iana" + }, + "application/dit": { + source: "iana" + }, + "application/dns": { + source: "iana" + }, + "application/dns+json": { + source: "iana", + compressible: true + }, + "application/dns-message": { + source: "iana" + }, + "application/docbook+xml": { + source: "apache", + compressible: true, + extensions: [ + "dbk" + ] + }, + "application/dots+cbor": { + source: "iana" + }, + "application/dskpp+xml": { + source: "iana", + compressible: true + }, + "application/dssc+der": { + source: "iana", + extensions: [ + "dssc" + ] + }, + "application/dssc+xml": { + source: "iana", + compressible: true, + extensions: [ + "xdssc" + ] + }, + "application/dvcs": { + source: "iana" + }, + "application/ecmascript": { + source: "iana", + compressible: true, + extensions: [ + "es", + "ecma" + ] + }, + "application/edi-consent": { + source: "iana" + }, + "application/edi-x12": { + source: "iana", + compressible: false + }, + "application/edifact": { + source: "iana", + compressible: false + }, + "application/efi": { + source: "iana" + }, + "application/elm+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/elm+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.cap+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/emergencycalldata.comment+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.control+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.deviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.ecall.msd": { + source: "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.serviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.subscriberinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.veds+xml": { + source: "iana", + compressible: true + }, + "application/emma+xml": { + source: "iana", + compressible: true, + extensions: [ + "emma" + ] + }, + "application/emotionml+xml": { + source: "iana", + compressible: true, + extensions: [ + "emotionml" + ] + }, + "application/encaprtp": { + source: "iana" + }, + "application/epp+xml": { + source: "iana", + compressible: true + }, + "application/epub+zip": { + source: "iana", + compressible: false, + extensions: [ + "epub" + ] + }, + "application/eshop": { + source: "iana" + }, + "application/exi": { + source: "iana", + extensions: [ + "exi" + ] + }, + "application/expect-ct-report+json": { + source: "iana", + compressible: true + }, + "application/express": { + source: "iana", + extensions: [ + "exp" + ] + }, + "application/fastinfoset": { + source: "iana" + }, + "application/fastsoap": { + source: "iana" + }, + "application/fdt+xml": { + source: "iana", + compressible: true, + extensions: [ + "fdt" + ] + }, + "application/fhir+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fhir+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fido.trusted-apps+json": { + compressible: true + }, + "application/fits": { + source: "iana" + }, + "application/flexfec": { + source: "iana" + }, + "application/font-sfnt": { + source: "iana" + }, + "application/font-tdpfr": { + source: "iana", + extensions: [ + "pfr" + ] + }, + "application/font-woff": { + source: "iana", + compressible: false + }, + "application/framework-attributes+xml": { + source: "iana", + compressible: true + }, + "application/geo+json": { + source: "iana", + compressible: true, + extensions: [ + "geojson" + ] + }, + "application/geo+json-seq": { + source: "iana" + }, + "application/geopackage+sqlite3": { + source: "iana" + }, + "application/geoxacml+xml": { + source: "iana", + compressible: true + }, + "application/gltf-buffer": { + source: "iana" + }, + "application/gml+xml": { + source: "iana", + compressible: true, + extensions: [ + "gml" + ] + }, + "application/gpx+xml": { + source: "apache", + compressible: true, + extensions: [ + "gpx" + ] + }, + "application/gxf": { + source: "apache", + extensions: [ + "gxf" + ] + }, + "application/gzip": { + source: "iana", + compressible: false, + extensions: [ + "gz" + ] + }, + "application/h224": { + source: "iana" + }, + "application/held+xml": { + source: "iana", + compressible: true + }, + "application/hjson": { + extensions: [ + "hjson" + ] + }, + "application/http": { + source: "iana" + }, + "application/hyperstudio": { + source: "iana", + extensions: [ + "stk" + ] + }, + "application/ibe-key-request+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pkg-reply+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pp-data": { + source: "iana" + }, + "application/iges": { + source: "iana" + }, + "application/im-iscomposing+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/index": { + source: "iana" + }, + "application/index.cmd": { + source: "iana" + }, + "application/index.obj": { + source: "iana" + }, + "application/index.response": { + source: "iana" + }, + "application/index.vnd": { + source: "iana" + }, + "application/inkml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ink", + "inkml" + ] + }, + "application/iotp": { + source: "iana" + }, + "application/ipfix": { + source: "iana", + extensions: [ + "ipfix" + ] + }, + "application/ipp": { + source: "iana" + }, + "application/isup": { + source: "iana" + }, + "application/its+xml": { + source: "iana", + compressible: true, + extensions: [ + "its" + ] + }, + "application/java-archive": { + source: "apache", + compressible: false, + extensions: [ + "jar", + "war", + "ear" + ] + }, + "application/java-serialized-object": { + source: "apache", + compressible: false, + extensions: [ + "ser" + ] + }, + "application/java-vm": { + source: "apache", + compressible: false, + extensions: [ + "class" + ] + }, + "application/javascript": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "js", + "mjs" + ] + }, + "application/jf2feed+json": { + source: "iana", + compressible: true + }, + "application/jose": { + source: "iana" + }, + "application/jose+json": { + source: "iana", + compressible: true + }, + "application/jrd+json": { + source: "iana", + compressible: true + }, + "application/jscalendar+json": { + source: "iana", + compressible: true + }, + "application/json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "json", + "map" + ] + }, + "application/json-patch+json": { + source: "iana", + compressible: true + }, + "application/json-seq": { + source: "iana" + }, + "application/json5": { + extensions: [ + "json5" + ] + }, + "application/jsonml+json": { + source: "apache", + compressible: true, + extensions: [ + "jsonml" + ] + }, + "application/jwk+json": { + source: "iana", + compressible: true + }, + "application/jwk-set+json": { + source: "iana", + compressible: true + }, + "application/jwt": { + source: "iana" + }, + "application/kpml-request+xml": { + source: "iana", + compressible: true + }, + "application/kpml-response+xml": { + source: "iana", + compressible: true + }, + "application/ld+json": { + source: "iana", + compressible: true, + extensions: [ + "jsonld" + ] + }, + "application/lgr+xml": { + source: "iana", + compressible: true, + extensions: [ + "lgr" + ] + }, + "application/link-format": { + source: "iana" + }, + "application/load-control+xml": { + source: "iana", + compressible: true + }, + "application/lost+xml": { + source: "iana", + compressible: true, + extensions: [ + "lostxml" + ] + }, + "application/lostsync+xml": { + source: "iana", + compressible: true + }, + "application/lpf+zip": { + source: "iana", + compressible: false + }, + "application/lxf": { + source: "iana" + }, + "application/mac-binhex40": { + source: "iana", + extensions: [ + "hqx" + ] + }, + "application/mac-compactpro": { + source: "apache", + extensions: [ + "cpt" + ] + }, + "application/macwriteii": { + source: "iana" + }, + "application/mads+xml": { + source: "iana", + compressible: true, + extensions: [ + "mads" + ] + }, + "application/manifest+json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "webmanifest" + ] + }, + "application/marc": { + source: "iana", + extensions: [ + "mrc" + ] + }, + "application/marcxml+xml": { + source: "iana", + compressible: true, + extensions: [ + "mrcx" + ] + }, + "application/mathematica": { + source: "iana", + extensions: [ + "ma", + "nb", + "mb" + ] + }, + "application/mathml+xml": { + source: "iana", + compressible: true, + extensions: [ + "mathml" + ] + }, + "application/mathml-content+xml": { + source: "iana", + compressible: true + }, + "application/mathml-presentation+xml": { + source: "iana", + compressible: true + }, + "application/mbms-associated-procedure-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-deregister+xml": { + source: "iana", + compressible: true + }, + "application/mbms-envelope+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-protection-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-reception-report+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-schedule+xml": { + source: "iana", + compressible: true + }, + "application/mbms-user-service-description+xml": { + source: "iana", + compressible: true + }, + "application/mbox": { + source: "iana", + extensions: [ + "mbox" + ] + }, + "application/media-policy-dataset+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpf" + ] + }, + "application/media_control+xml": { + source: "iana", + compressible: true + }, + "application/mediaservercontrol+xml": { + source: "iana", + compressible: true, + extensions: [ + "mscml" + ] + }, + "application/merge-patch+json": { + source: "iana", + compressible: true + }, + "application/metalink+xml": { + source: "apache", + compressible: true, + extensions: [ + "metalink" + ] + }, + "application/metalink4+xml": { + source: "iana", + compressible: true, + extensions: [ + "meta4" + ] + }, + "application/mets+xml": { + source: "iana", + compressible: true, + extensions: [ + "mets" + ] + }, + "application/mf4": { + source: "iana" + }, + "application/mikey": { + source: "iana" + }, + "application/mipc": { + source: "iana" + }, + "application/missing-blocks+cbor-seq": { + source: "iana" + }, + "application/mmt-aei+xml": { + source: "iana", + compressible: true, + extensions: [ + "maei" + ] + }, + "application/mmt-usd+xml": { + source: "iana", + compressible: true, + extensions: [ + "musd" + ] + }, + "application/mods+xml": { + source: "iana", + compressible: true, + extensions: [ + "mods" + ] + }, + "application/moss-keys": { + source: "iana" + }, + "application/moss-signature": { + source: "iana" + }, + "application/mosskey-data": { + source: "iana" + }, + "application/mosskey-request": { + source: "iana" + }, + "application/mp21": { + source: "iana", + extensions: [ + "m21", + "mp21" + ] + }, + "application/mp4": { + source: "iana", + extensions: [ + "mp4s", + "m4p" + ] + }, + "application/mpeg4-generic": { + source: "iana" + }, + "application/mpeg4-iod": { + source: "iana" + }, + "application/mpeg4-iod-xmt": { + source: "iana" + }, + "application/mrb-consumer+xml": { + source: "iana", + compressible: true + }, + "application/mrb-publish+xml": { + source: "iana", + compressible: true + }, + "application/msc-ivr+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msc-mixer+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msword": { + source: "iana", + compressible: false, + extensions: [ + "doc", + "dot" + ] + }, + "application/mud+json": { + source: "iana", + compressible: true + }, + "application/multipart-core": { + source: "iana" + }, + "application/mxf": { + source: "iana", + extensions: [ + "mxf" + ] + }, + "application/n-quads": { + source: "iana", + extensions: [ + "nq" + ] + }, + "application/n-triples": { + source: "iana", + extensions: [ + "nt" + ] + }, + "application/nasdata": { + source: "iana" + }, + "application/news-checkgroups": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-groupinfo": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-transmission": { + source: "iana" + }, + "application/nlsml+xml": { + source: "iana", + compressible: true + }, + "application/node": { + source: "iana", + extensions: [ + "cjs" + ] + }, + "application/nss": { + source: "iana" + }, + "application/oauth-authz-req+jwt": { + source: "iana" + }, + "application/oblivious-dns-message": { + source: "iana" + }, + "application/ocsp-request": { + source: "iana" + }, + "application/ocsp-response": { + source: "iana" + }, + "application/octet-stream": { + source: "iana", + compressible: false, + extensions: [ + "bin", + "dms", + "lrf", + "mar", + "so", + "dist", + "distz", + "pkg", + "bpk", + "dump", + "elc", + "deploy", + "exe", + "dll", + "deb", + "dmg", + "iso", + "img", + "msi", + "msp", + "msm", + "buffer" + ] + }, + "application/oda": { + source: "iana", + extensions: [ + "oda" + ] + }, + "application/odm+xml": { + source: "iana", + compressible: true + }, + "application/odx": { + source: "iana" + }, + "application/oebps-package+xml": { + source: "iana", + compressible: true, + extensions: [ + "opf" + ] + }, + "application/ogg": { + source: "iana", + compressible: false, + extensions: [ + "ogx" + ] + }, + "application/omdoc+xml": { + source: "apache", + compressible: true, + extensions: [ + "omdoc" + ] + }, + "application/onenote": { + source: "apache", + extensions: [ + "onetoc", + "onetoc2", + "onetmp", + "onepkg" + ] + }, + "application/opc-nodeset+xml": { + source: "iana", + compressible: true + }, + "application/oscore": { + source: "iana" + }, + "application/oxps": { + source: "iana", + extensions: [ + "oxps" + ] + }, + "application/p21": { + source: "iana" + }, + "application/p21+zip": { + source: "iana", + compressible: false + }, + "application/p2p-overlay+xml": { + source: "iana", + compressible: true, + extensions: [ + "relo" + ] + }, + "application/parityfec": { + source: "iana" + }, + "application/passport": { + source: "iana" + }, + "application/patch-ops-error+xml": { + source: "iana", + compressible: true, + extensions: [ + "xer" + ] + }, + "application/pdf": { + source: "iana", + compressible: false, + extensions: [ + "pdf" + ] + }, + "application/pdx": { + source: "iana" + }, + "application/pem-certificate-chain": { + source: "iana" + }, + "application/pgp-encrypted": { + source: "iana", + compressible: false, + extensions: [ + "pgp" + ] + }, + "application/pgp-keys": { + source: "iana", + extensions: [ + "asc" + ] + }, + "application/pgp-signature": { + source: "iana", + extensions: [ + "asc", + "sig" + ] + }, + "application/pics-rules": { + source: "apache", + extensions: [ + "prf" + ] + }, + "application/pidf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pidf-diff+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pkcs10": { + source: "iana", + extensions: [ + "p10" + ] + }, + "application/pkcs12": { + source: "iana" + }, + "application/pkcs7-mime": { + source: "iana", + extensions: [ + "p7m", + "p7c" + ] + }, + "application/pkcs7-signature": { + source: "iana", + extensions: [ + "p7s" + ] + }, + "application/pkcs8": { + source: "iana", + extensions: [ + "p8" + ] + }, + "application/pkcs8-encrypted": { + source: "iana" + }, + "application/pkix-attr-cert": { + source: "iana", + extensions: [ + "ac" + ] + }, + "application/pkix-cert": { + source: "iana", + extensions: [ + "cer" + ] + }, + "application/pkix-crl": { + source: "iana", + extensions: [ + "crl" + ] + }, + "application/pkix-pkipath": { + source: "iana", + extensions: [ + "pkipath" + ] + }, + "application/pkixcmp": { + source: "iana", + extensions: [ + "pki" + ] + }, + "application/pls+xml": { + source: "iana", + compressible: true, + extensions: [ + "pls" + ] + }, + "application/poc-settings+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/postscript": { + source: "iana", + compressible: true, + extensions: [ + "ai", + "eps", + "ps" + ] + }, + "application/ppsp-tracker+json": { + source: "iana", + compressible: true + }, + "application/problem+json": { + source: "iana", + compressible: true + }, + "application/problem+xml": { + source: "iana", + compressible: true + }, + "application/provenance+xml": { + source: "iana", + compressible: true, + extensions: [ + "provx" + ] + }, + "application/prs.alvestrand.titrax-sheet": { + source: "iana" + }, + "application/prs.cww": { + source: "iana", + extensions: [ + "cww" + ] + }, + "application/prs.cyn": { + source: "iana", + charset: "7-BIT" + }, + "application/prs.hpub+zip": { + source: "iana", + compressible: false + }, + "application/prs.nprend": { + source: "iana" + }, + "application/prs.plucker": { + source: "iana" + }, + "application/prs.rdf-xml-crypt": { + source: "iana" + }, + "application/prs.xsf+xml": { + source: "iana", + compressible: true + }, + "application/pskc+xml": { + source: "iana", + compressible: true, + extensions: [ + "pskcxml" + ] + }, + "application/pvd+json": { + source: "iana", + compressible: true + }, + "application/qsig": { + source: "iana" + }, + "application/raml+yaml": { + compressible: true, + extensions: [ + "raml" + ] + }, + "application/raptorfec": { + source: "iana" + }, + "application/rdap+json": { + source: "iana", + compressible: true + }, + "application/rdf+xml": { + source: "iana", + compressible: true, + extensions: [ + "rdf", + "owl" + ] + }, + "application/reginfo+xml": { + source: "iana", + compressible: true, + extensions: [ + "rif" + ] + }, + "application/relax-ng-compact-syntax": { + source: "iana", + extensions: [ + "rnc" + ] + }, + "application/remote-printing": { + source: "iana" + }, + "application/reputon+json": { + source: "iana", + compressible: true + }, + "application/resource-lists+xml": { + source: "iana", + compressible: true, + extensions: [ + "rl" + ] + }, + "application/resource-lists-diff+xml": { + source: "iana", + compressible: true, + extensions: [ + "rld" + ] + }, + "application/rfc+xml": { + source: "iana", + compressible: true + }, + "application/riscos": { + source: "iana" + }, + "application/rlmi+xml": { + source: "iana", + compressible: true + }, + "application/rls-services+xml": { + source: "iana", + compressible: true, + extensions: [ + "rs" + ] + }, + "application/route-apd+xml": { + source: "iana", + compressible: true, + extensions: [ + "rapd" + ] + }, + "application/route-s-tsid+xml": { + source: "iana", + compressible: true, + extensions: [ + "sls" + ] + }, + "application/route-usd+xml": { + source: "iana", + compressible: true, + extensions: [ + "rusd" + ] + }, + "application/rpki-ghostbusters": { + source: "iana", + extensions: [ + "gbr" + ] + }, + "application/rpki-manifest": { + source: "iana", + extensions: [ + "mft" + ] + }, + "application/rpki-publication": { + source: "iana" + }, + "application/rpki-roa": { + source: "iana", + extensions: [ + "roa" + ] + }, + "application/rpki-updown": { + source: "iana" + }, + "application/rsd+xml": { + source: "apache", + compressible: true, + extensions: [ + "rsd" + ] + }, + "application/rss+xml": { + source: "apache", + compressible: true, + extensions: [ + "rss" + ] + }, + "application/rtf": { + source: "iana", + compressible: true, + extensions: [ + "rtf" + ] + }, + "application/rtploopback": { + source: "iana" + }, + "application/rtx": { + source: "iana" + }, + "application/samlassertion+xml": { + source: "iana", + compressible: true + }, + "application/samlmetadata+xml": { + source: "iana", + compressible: true + }, + "application/sarif+json": { + source: "iana", + compressible: true + }, + "application/sarif-external-properties+json": { + source: "iana", + compressible: true + }, + "application/sbe": { + source: "iana" + }, + "application/sbml+xml": { + source: "iana", + compressible: true, + extensions: [ + "sbml" + ] + }, + "application/scaip+xml": { + source: "iana", + compressible: true + }, + "application/scim+json": { + source: "iana", + compressible: true + }, + "application/scvp-cv-request": { + source: "iana", + extensions: [ + "scq" + ] + }, + "application/scvp-cv-response": { + source: "iana", + extensions: [ + "scs" + ] + }, + "application/scvp-vp-request": { + source: "iana", + extensions: [ + "spq" + ] + }, + "application/scvp-vp-response": { + source: "iana", + extensions: [ + "spp" + ] + }, + "application/sdp": { + source: "iana", + extensions: [ + "sdp" + ] + }, + "application/secevent+jwt": { + source: "iana" + }, + "application/senml+cbor": { + source: "iana" + }, + "application/senml+json": { + source: "iana", + compressible: true + }, + "application/senml+xml": { + source: "iana", + compressible: true, + extensions: [ + "senmlx" + ] + }, + "application/senml-etch+cbor": { + source: "iana" + }, + "application/senml-etch+json": { + source: "iana", + compressible: true + }, + "application/senml-exi": { + source: "iana" + }, + "application/sensml+cbor": { + source: "iana" + }, + "application/sensml+json": { + source: "iana", + compressible: true + }, + "application/sensml+xml": { + source: "iana", + compressible: true, + extensions: [ + "sensmlx" + ] + }, + "application/sensml-exi": { + source: "iana" + }, + "application/sep+xml": { + source: "iana", + compressible: true + }, + "application/sep-exi": { + source: "iana" + }, + "application/session-info": { + source: "iana" + }, + "application/set-payment": { + source: "iana" + }, + "application/set-payment-initiation": { + source: "iana", + extensions: [ + "setpay" + ] + }, + "application/set-registration": { + source: "iana" + }, + "application/set-registration-initiation": { + source: "iana", + extensions: [ + "setreg" + ] + }, + "application/sgml": { + source: "iana" + }, + "application/sgml-open-catalog": { + source: "iana" + }, + "application/shf+xml": { + source: "iana", + compressible: true, + extensions: [ + "shf" + ] + }, + "application/sieve": { + source: "iana", + extensions: [ + "siv", + "sieve" + ] + }, + "application/simple-filter+xml": { + source: "iana", + compressible: true + }, + "application/simple-message-summary": { + source: "iana" + }, + "application/simplesymbolcontainer": { + source: "iana" + }, + "application/sipc": { + source: "iana" + }, + "application/slate": { + source: "iana" + }, + "application/smil": { + source: "iana" + }, + "application/smil+xml": { + source: "iana", + compressible: true, + extensions: [ + "smi", + "smil" + ] + }, + "application/smpte336m": { + source: "iana" + }, + "application/soap+fastinfoset": { + source: "iana" + }, + "application/soap+xml": { + source: "iana", + compressible: true + }, + "application/sparql-query": { + source: "iana", + extensions: [ + "rq" + ] + }, + "application/sparql-results+xml": { + source: "iana", + compressible: true, + extensions: [ + "srx" + ] + }, + "application/spdx+json": { + source: "iana", + compressible: true + }, + "application/spirits-event+xml": { + source: "iana", + compressible: true + }, + "application/sql": { + source: "iana" + }, + "application/srgs": { + source: "iana", + extensions: [ + "gram" + ] + }, + "application/srgs+xml": { + source: "iana", + compressible: true, + extensions: [ + "grxml" + ] + }, + "application/sru+xml": { + source: "iana", + compressible: true, + extensions: [ + "sru" + ] + }, + "application/ssdl+xml": { + source: "apache", + compressible: true, + extensions: [ + "ssdl" + ] + }, + "application/ssml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ssml" + ] + }, + "application/stix+json": { + source: "iana", + compressible: true + }, + "application/swid+xml": { + source: "iana", + compressible: true, + extensions: [ + "swidtag" + ] + }, + "application/tamp-apex-update": { + source: "iana" + }, + "application/tamp-apex-update-confirm": { + source: "iana" + }, + "application/tamp-community-update": { + source: "iana" + }, + "application/tamp-community-update-confirm": { + source: "iana" + }, + "application/tamp-error": { + source: "iana" + }, + "application/tamp-sequence-adjust": { + source: "iana" + }, + "application/tamp-sequence-adjust-confirm": { + source: "iana" + }, + "application/tamp-status-query": { + source: "iana" + }, + "application/tamp-status-response": { + source: "iana" + }, + "application/tamp-update": { + source: "iana" + }, + "application/tamp-update-confirm": { + source: "iana" + }, + "application/tar": { + compressible: true + }, + "application/taxii+json": { + source: "iana", + compressible: true + }, + "application/td+json": { + source: "iana", + compressible: true + }, + "application/tei+xml": { + source: "iana", + compressible: true, + extensions: [ + "tei", + "teicorpus" + ] + }, + "application/tetra_isi": { + source: "iana" + }, + "application/thraud+xml": { + source: "iana", + compressible: true, + extensions: [ + "tfi" + ] + }, + "application/timestamp-query": { + source: "iana" + }, + "application/timestamp-reply": { + source: "iana" + }, + "application/timestamped-data": { + source: "iana", + extensions: [ + "tsd" + ] + }, + "application/tlsrpt+gzip": { + source: "iana" + }, + "application/tlsrpt+json": { + source: "iana", + compressible: true + }, + "application/tnauthlist": { + source: "iana" + }, + "application/token-introspection+jwt": { + source: "iana" + }, + "application/toml": { + compressible: true, + extensions: [ + "toml" + ] + }, + "application/trickle-ice-sdpfrag": { + source: "iana" + }, + "application/trig": { + source: "iana", + extensions: [ + "trig" + ] + }, + "application/ttml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ttml" + ] + }, + "application/tve-trigger": { + source: "iana" + }, + "application/tzif": { + source: "iana" + }, + "application/tzif-leap": { + source: "iana" + }, + "application/ubjson": { + compressible: false, + extensions: [ + "ubj" + ] + }, + "application/ulpfec": { + source: "iana" + }, + "application/urc-grpsheet+xml": { + source: "iana", + compressible: true + }, + "application/urc-ressheet+xml": { + source: "iana", + compressible: true, + extensions: [ + "rsheet" + ] + }, + "application/urc-targetdesc+xml": { + source: "iana", + compressible: true, + extensions: [ + "td" + ] + }, + "application/urc-uisocketdesc+xml": { + source: "iana", + compressible: true + }, + "application/vcard+json": { + source: "iana", + compressible: true + }, + "application/vcard+xml": { + source: "iana", + compressible: true + }, + "application/vemmi": { + source: "iana" + }, + "application/vividence.scriptfile": { + source: "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + source: "iana", + compressible: true, + extensions: [ + "1km" + ] + }, + "application/vnd.3gpp-prose+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-v2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.5gnas": { + source: "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.bsf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gmop+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gtpc": { + source: "iana" + }, + "application/vnd.3gpp.interworking-data": { + source: "iana" + }, + "application/vnd.3gpp.lpp": { + source: "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-payload": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-signalling": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mid-call+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ngap": { + source: "iana" + }, + "application/vnd.3gpp.pfcp": { + source: "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + source: "iana", + extensions: [ + "plb" + ] + }, + "application/vnd.3gpp.pic-bw-small": { + source: "iana", + extensions: [ + "psb" + ] + }, + "application/vnd.3gpp.pic-bw-var": { + source: "iana", + extensions: [ + "pvb" + ] + }, + "application/vnd.3gpp.s1ap": { + source: "iana" + }, + "application/vnd.3gpp.sms": { + source: "iana" + }, + "application/vnd.3gpp.sms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ussd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.sms": { + source: "iana" + }, + "application/vnd.3gpp2.tcap": { + source: "iana", + extensions: [ + "tcap" + ] + }, + "application/vnd.3lightssoftware.imagescal": { + source: "iana" + }, + "application/vnd.3m.post-it-notes": { + source: "iana", + extensions: [ + "pwn" + ] + }, + "application/vnd.accpac.simply.aso": { + source: "iana", + extensions: [ + "aso" + ] + }, + "application/vnd.accpac.simply.imp": { + source: "iana", + extensions: [ + "imp" + ] + }, + "application/vnd.acucobol": { + source: "iana", + extensions: [ + "acu" + ] + }, + "application/vnd.acucorp": { + source: "iana", + extensions: [ + "atc", + "acutc" + ] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + source: "apache", + compressible: false, + extensions: [ + "air" + ] + }, + "application/vnd.adobe.flash.movie": { + source: "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + source: "iana", + extensions: [ + "fcdt" + ] + }, + "application/vnd.adobe.fxp": { + source: "iana", + extensions: [ + "fxp", + "fxpl" + ] + }, + "application/vnd.adobe.partial-upload": { + source: "iana" + }, + "application/vnd.adobe.xdp+xml": { + source: "iana", + compressible: true, + extensions: [ + "xdp" + ] + }, + "application/vnd.adobe.xfdf": { + source: "iana", + extensions: [ + "xfdf" + ] + }, + "application/vnd.aether.imp": { + source: "iana" + }, + "application/vnd.afpc.afplinedata": { + source: "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + source: "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + source: "iana" + }, + "application/vnd.afpc.foca-charset": { + source: "iana" + }, + "application/vnd.afpc.foca-codedfont": { + source: "iana" + }, + "application/vnd.afpc.foca-codepage": { + source: "iana" + }, + "application/vnd.afpc.modca": { + source: "iana" + }, + "application/vnd.afpc.modca-cmtable": { + source: "iana" + }, + "application/vnd.afpc.modca-formdef": { + source: "iana" + }, + "application/vnd.afpc.modca-mediummap": { + source: "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + source: "iana" + }, + "application/vnd.afpc.modca-overlay": { + source: "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + source: "iana" + }, + "application/vnd.age": { + source: "iana", + extensions: [ + "age" + ] + }, + "application/vnd.ah-barcode": { + source: "iana" + }, + "application/vnd.ahead.space": { + source: "iana", + extensions: [ + "ahead" + ] + }, + "application/vnd.airzip.filesecure.azf": { + source: "iana", + extensions: [ + "azf" + ] + }, + "application/vnd.airzip.filesecure.azs": { + source: "iana", + extensions: [ + "azs" + ] + }, + "application/vnd.amadeus+json": { + source: "iana", + compressible: true + }, + "application/vnd.amazon.ebook": { + source: "apache", + extensions: [ + "azw" + ] + }, + "application/vnd.amazon.mobi8-ebook": { + source: "iana" + }, + "application/vnd.americandynamics.acc": { + source: "iana", + extensions: [ + "acc" + ] + }, + "application/vnd.amiga.ami": { + source: "iana", + extensions: [ + "ami" + ] + }, + "application/vnd.amundsen.maze+xml": { + source: "iana", + compressible: true + }, + "application/vnd.android.ota": { + source: "iana" + }, + "application/vnd.android.package-archive": { + source: "apache", + compressible: false, + extensions: [ + "apk" + ] + }, + "application/vnd.anki": { + source: "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + source: "iana", + extensions: [ + "cii" + ] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + source: "apache", + extensions: [ + "fti" + ] + }, + "application/vnd.antix.game-component": { + source: "iana", + extensions: [ + "atx" + ] + }, + "application/vnd.apache.arrow.file": { + source: "iana" + }, + "application/vnd.apache.arrow.stream": { + source: "iana" + }, + "application/vnd.apache.thrift.binary": { + source: "iana" + }, + "application/vnd.apache.thrift.compact": { + source: "iana" + }, + "application/vnd.apache.thrift.json": { + source: "iana" + }, + "application/vnd.api+json": { + source: "iana", + compressible: true + }, + "application/vnd.aplextor.warrp+json": { + source: "iana", + compressible: true + }, + "application/vnd.apothekende.reservation+json": { + source: "iana", + compressible: true + }, + "application/vnd.apple.installer+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpkg" + ] + }, + "application/vnd.apple.keynote": { + source: "iana", + extensions: [ + "key" + ] + }, + "application/vnd.apple.mpegurl": { + source: "iana", + extensions: [ + "m3u8" + ] + }, + "application/vnd.apple.numbers": { + source: "iana", + extensions: [ + "numbers" + ] + }, + "application/vnd.apple.pages": { + source: "iana", + extensions: [ + "pages" + ] + }, + "application/vnd.apple.pkpass": { + compressible: false, + extensions: [ + "pkpass" + ] + }, + "application/vnd.arastra.swi": { + source: "iana" + }, + "application/vnd.aristanetworks.swi": { + source: "iana", + extensions: [ + "swi" + ] + }, + "application/vnd.artisan+json": { + source: "iana", + compressible: true + }, + "application/vnd.artsquare": { + source: "iana" + }, + "application/vnd.astraea-software.iota": { + source: "iana", + extensions: [ + "iota" + ] + }, + "application/vnd.audiograph": { + source: "iana", + extensions: [ + "aep" + ] + }, + "application/vnd.autopackage": { + source: "iana" + }, + "application/vnd.avalon+json": { + source: "iana", + compressible: true + }, + "application/vnd.avistar+xml": { + source: "iana", + compressible: true + }, + "application/vnd.balsamiq.bmml+xml": { + source: "iana", + compressible: true, + extensions: [ + "bmml" + ] + }, + "application/vnd.balsamiq.bmpr": { + source: "iana" + }, + "application/vnd.banana-accounting": { + source: "iana" + }, + "application/vnd.bbf.usp.error": { + source: "iana" + }, + "application/vnd.bbf.usp.msg": { + source: "iana" + }, + "application/vnd.bbf.usp.msg+json": { + source: "iana", + compressible: true + }, + "application/vnd.bekitzur-stech+json": { + source: "iana", + compressible: true + }, + "application/vnd.bint.med-content": { + source: "iana" + }, + "application/vnd.biopax.rdf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.blink-idb-value-wrapper": { + source: "iana" + }, + "application/vnd.blueice.multipass": { + source: "iana", + extensions: [ + "mpm" + ] + }, + "application/vnd.bluetooth.ep.oob": { + source: "iana" + }, + "application/vnd.bluetooth.le.oob": { + source: "iana" + }, + "application/vnd.bmi": { + source: "iana", + extensions: [ + "bmi" + ] + }, + "application/vnd.bpf": { + source: "iana" + }, + "application/vnd.bpf3": { + source: "iana" + }, + "application/vnd.businessobjects": { + source: "iana", + extensions: [ + "rep" + ] + }, + "application/vnd.byu.uapi+json": { + source: "iana", + compressible: true + }, + "application/vnd.cab-jscript": { + source: "iana" + }, + "application/vnd.canon-cpdl": { + source: "iana" + }, + "application/vnd.canon-lips": { + source: "iana" + }, + "application/vnd.capasystems-pg+json": { + source: "iana", + compressible: true + }, + "application/vnd.cendio.thinlinc.clientconf": { + source: "iana" + }, + "application/vnd.century-systems.tcp_stream": { + source: "iana" + }, + "application/vnd.chemdraw+xml": { + source: "iana", + compressible: true, + extensions: [ + "cdxml" + ] + }, + "application/vnd.chess-pgn": { + source: "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + source: "iana", + extensions: [ + "mmd" + ] + }, + "application/vnd.ciedi": { + source: "iana" + }, + "application/vnd.cinderella": { + source: "iana", + extensions: [ + "cdy" + ] + }, + "application/vnd.cirpack.isdn-ext": { + source: "iana" + }, + "application/vnd.citationstyles.style+xml": { + source: "iana", + compressible: true, + extensions: [ + "csl" + ] + }, + "application/vnd.claymore": { + source: "iana", + extensions: [ + "cla" + ] + }, + "application/vnd.cloanto.rp9": { + source: "iana", + extensions: [ + "rp9" + ] + }, + "application/vnd.clonk.c4group": { + source: "iana", + extensions: [ + "c4g", + "c4d", + "c4f", + "c4p", + "c4u" + ] + }, + "application/vnd.cluetrust.cartomobile-config": { + source: "iana", + extensions: [ + "c11amc" + ] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + source: "iana", + extensions: [ + "c11amz" + ] + }, + "application/vnd.coffeescript": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + source: "iana" + }, + "application/vnd.collection+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.doc+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.next+json": { + source: "iana", + compressible: true + }, + "application/vnd.comicbook+zip": { + source: "iana", + compressible: false + }, + "application/vnd.comicbook-rar": { + source: "iana" + }, + "application/vnd.commerce-battelle": { + source: "iana" + }, + "application/vnd.commonspace": { + source: "iana", + extensions: [ + "csp" + ] + }, + "application/vnd.contact.cmsg": { + source: "iana", + extensions: [ + "cdbcmsg" + ] + }, + "application/vnd.coreos.ignition+json": { + source: "iana", + compressible: true + }, + "application/vnd.cosmocaller": { + source: "iana", + extensions: [ + "cmc" + ] + }, + "application/vnd.crick.clicker": { + source: "iana", + extensions: [ + "clkx" + ] + }, + "application/vnd.crick.clicker.keyboard": { + source: "iana", + extensions: [ + "clkk" + ] + }, + "application/vnd.crick.clicker.palette": { + source: "iana", + extensions: [ + "clkp" + ] + }, + "application/vnd.crick.clicker.template": { + source: "iana", + extensions: [ + "clkt" + ] + }, + "application/vnd.crick.clicker.wordbank": { + source: "iana", + extensions: [ + "clkw" + ] + }, + "application/vnd.criticaltools.wbs+xml": { + source: "iana", + compressible: true, + extensions: [ + "wbs" + ] + }, + "application/vnd.cryptii.pipe+json": { + source: "iana", + compressible: true + }, + "application/vnd.crypto-shade-file": { + source: "iana" + }, + "application/vnd.cryptomator.encrypted": { + source: "iana" + }, + "application/vnd.cryptomator.vault": { + source: "iana" + }, + "application/vnd.ctc-posml": { + source: "iana", + extensions: [ + "pml" + ] + }, + "application/vnd.ctct.ws+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cups-pdf": { + source: "iana" + }, + "application/vnd.cups-postscript": { + source: "iana" + }, + "application/vnd.cups-ppd": { + source: "iana", + extensions: [ + "ppd" + ] + }, + "application/vnd.cups-raster": { + source: "iana" + }, + "application/vnd.cups-raw": { + source: "iana" + }, + "application/vnd.curl": { + source: "iana" + }, + "application/vnd.curl.car": { + source: "apache", + extensions: [ + "car" + ] + }, + "application/vnd.curl.pcurl": { + source: "apache", + extensions: [ + "pcurl" + ] + }, + "application/vnd.cyan.dean.root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cybank": { + source: "iana" + }, + "application/vnd.cyclonedx+json": { + source: "iana", + compressible: true + }, + "application/vnd.cyclonedx+xml": { + source: "iana", + compressible: true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + source: "iana", + compressible: false + }, + "application/vnd.d3m-dataset": { + source: "iana" + }, + "application/vnd.d3m-problem": { + source: "iana" + }, + "application/vnd.dart": { + source: "iana", + compressible: true, + extensions: [ + "dart" + ] + }, + "application/vnd.data-vision.rdz": { + source: "iana", + extensions: [ + "rdz" + ] + }, + "application/vnd.datapackage+json": { + source: "iana", + compressible: true + }, + "application/vnd.dataresource+json": { + source: "iana", + compressible: true + }, + "application/vnd.dbf": { + source: "iana", + extensions: [ + "dbf" + ] + }, + "application/vnd.debian.binary-package": { + source: "iana" + }, + "application/vnd.dece.data": { + source: "iana", + extensions: [ + "uvf", + "uvvf", + "uvd", + "uvvd" + ] + }, + "application/vnd.dece.ttml+xml": { + source: "iana", + compressible: true, + extensions: [ + "uvt", + "uvvt" + ] + }, + "application/vnd.dece.unspecified": { + source: "iana", + extensions: [ + "uvx", + "uvvx" + ] + }, + "application/vnd.dece.zip": { + source: "iana", + extensions: [ + "uvz", + "uvvz" + ] + }, + "application/vnd.denovo.fcselayout-link": { + source: "iana", + extensions: [ + "fe_launch" + ] + }, + "application/vnd.desmume.movie": { + source: "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + source: "iana" + }, + "application/vnd.dm.delegation+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dna": { + source: "iana", + extensions: [ + "dna" + ] + }, + "application/vnd.document+json": { + source: "iana", + compressible: true + }, + "application/vnd.dolby.mlp": { + source: "apache", + extensions: [ + "mlp" + ] + }, + "application/vnd.dolby.mobile.1": { + source: "iana" + }, + "application/vnd.dolby.mobile.2": { + source: "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + source: "iana" + }, + "application/vnd.dpgraph": { + source: "iana", + extensions: [ + "dpg" + ] + }, + "application/vnd.dreamfactory": { + source: "iana", + extensions: [ + "dfac" + ] + }, + "application/vnd.drive+json": { + source: "iana", + compressible: true + }, + "application/vnd.ds-keypoint": { + source: "apache", + extensions: [ + "kpxx" + ] + }, + "application/vnd.dtg.local": { + source: "iana" + }, + "application/vnd.dtg.local.flash": { + source: "iana" + }, + "application/vnd.dtg.local.html": { + source: "iana" + }, + "application/vnd.dvb.ait": { + source: "iana", + extensions: [ + "ait" + ] + }, + "application/vnd.dvb.dvbisl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.dvbj": { + source: "iana" + }, + "application/vnd.dvb.esgcontainer": { + source: "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + source: "iana" + }, + "application/vnd.dvb.ipdcroaming": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + source: "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-container+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-generic+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-init+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.pfr": { + source: "iana" + }, + "application/vnd.dvb.service": { + source: "iana", + extensions: [ + "svc" + ] + }, + "application/vnd.dxr": { + source: "iana" + }, + "application/vnd.dynageo": { + source: "iana", + extensions: [ + "geo" + ] + }, + "application/vnd.dzr": { + source: "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + source: "iana" + }, + "application/vnd.ecdis-update": { + source: "iana" + }, + "application/vnd.ecip.rlp": { + source: "iana" + }, + "application/vnd.eclipse.ditto+json": { + source: "iana", + compressible: true + }, + "application/vnd.ecowin.chart": { + source: "iana", + extensions: [ + "mag" + ] + }, + "application/vnd.ecowin.filerequest": { + source: "iana" + }, + "application/vnd.ecowin.fileupdate": { + source: "iana" + }, + "application/vnd.ecowin.series": { + source: "iana" + }, + "application/vnd.ecowin.seriesrequest": { + source: "iana" + }, + "application/vnd.ecowin.seriesupdate": { + source: "iana" + }, + "application/vnd.efi.img": { + source: "iana" + }, + "application/vnd.efi.iso": { + source: "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + source: "iana", + compressible: true + }, + "application/vnd.enliven": { + source: "iana", + extensions: [ + "nml" + ] + }, + "application/vnd.enphase.envoy": { + source: "iana" + }, + "application/vnd.eprints.data+xml": { + source: "iana", + compressible: true + }, + "application/vnd.epson.esf": { + source: "iana", + extensions: [ + "esf" + ] + }, + "application/vnd.epson.msf": { + source: "iana", + extensions: [ + "msf" + ] + }, + "application/vnd.epson.quickanime": { + source: "iana", + extensions: [ + "qam" + ] + }, + "application/vnd.epson.salt": { + source: "iana", + extensions: [ + "slt" + ] + }, + "application/vnd.epson.ssf": { + source: "iana", + extensions: [ + "ssf" + ] + }, + "application/vnd.ericsson.quickcall": { + source: "iana" + }, + "application/vnd.espass-espass+zip": { + source: "iana", + compressible: false + }, + "application/vnd.eszigno3+xml": { + source: "iana", + compressible: true, + extensions: [ + "es3", + "et3" + ] + }, + "application/vnd.etsi.aoc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.asic-e+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.asic-s+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.cug+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvcommand+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvservice+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsync+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mcid+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mheg5": { + source: "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.pstn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.sci+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.simservs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.timestamp-token": { + source: "iana" + }, + "application/vnd.etsi.tsl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.tsl.der": { + source: "iana" + }, + "application/vnd.eu.kasparian.car+json": { + source: "iana", + compressible: true + }, + "application/vnd.eudora.data": { + source: "iana" + }, + "application/vnd.evolv.ecig.profile": { + source: "iana" + }, + "application/vnd.evolv.ecig.settings": { + source: "iana" + }, + "application/vnd.evolv.ecig.theme": { + source: "iana" + }, + "application/vnd.exstream-empower+zip": { + source: "iana", + compressible: false + }, + "application/vnd.exstream-package": { + source: "iana" + }, + "application/vnd.ezpix-album": { + source: "iana", + extensions: [ + "ez2" + ] + }, + "application/vnd.ezpix-package": { + source: "iana", + extensions: [ + "ez3" + ] + }, + "application/vnd.f-secure.mobile": { + source: "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + source: "iana", + compressible: false + }, + "application/vnd.fastcopy-disk-image": { + source: "iana" + }, + "application/vnd.fdf": { + source: "iana", + extensions: [ + "fdf" + ] + }, + "application/vnd.fdsn.mseed": { + source: "iana", + extensions: [ + "mseed" + ] + }, + "application/vnd.fdsn.seed": { + source: "iana", + extensions: [ + "seed", + "dataless" + ] + }, + "application/vnd.ffsns": { + source: "iana" + }, + "application/vnd.ficlab.flb+zip": { + source: "iana", + compressible: false + }, + "application/vnd.filmit.zfc": { + source: "iana" + }, + "application/vnd.fints": { + source: "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + source: "iana" + }, + "application/vnd.flographit": { + source: "iana", + extensions: [ + "gph" + ] + }, + "application/vnd.fluxtime.clip": { + source: "iana", + extensions: [ + "ftc" + ] + }, + "application/vnd.font-fontforge-sfd": { + source: "iana" + }, + "application/vnd.framemaker": { + source: "iana", + extensions: [ + "fm", + "frame", + "maker", + "book" + ] + }, + "application/vnd.frogans.fnc": { + source: "iana", + extensions: [ + "fnc" + ] + }, + "application/vnd.frogans.ltf": { + source: "iana", + extensions: [ + "ltf" + ] + }, + "application/vnd.fsc.weblaunch": { + source: "iana", + extensions: [ + "fsc" + ] + }, + "application/vnd.fujifilm.fb.docuworks": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + source: "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.fujitsu.oasys": { + source: "iana", + extensions: [ + "oas" + ] + }, + "application/vnd.fujitsu.oasys2": { + source: "iana", + extensions: [ + "oa2" + ] + }, + "application/vnd.fujitsu.oasys3": { + source: "iana", + extensions: [ + "oa3" + ] + }, + "application/vnd.fujitsu.oasysgp": { + source: "iana", + extensions: [ + "fg5" + ] + }, + "application/vnd.fujitsu.oasysprs": { + source: "iana", + extensions: [ + "bh2" + ] + }, + "application/vnd.fujixerox.art-ex": { + source: "iana" + }, + "application/vnd.fujixerox.art4": { + source: "iana" + }, + "application/vnd.fujixerox.ddd": { + source: "iana", + extensions: [ + "ddd" + ] + }, + "application/vnd.fujixerox.docuworks": { + source: "iana", + extensions: [ + "xdw" + ] + }, + "application/vnd.fujixerox.docuworks.binder": { + source: "iana", + extensions: [ + "xbd" + ] + }, + "application/vnd.fujixerox.docuworks.container": { + source: "iana" + }, + "application/vnd.fujixerox.hbpl": { + source: "iana" + }, + "application/vnd.fut-misnet": { + source: "iana" + }, + "application/vnd.futoin+cbor": { + source: "iana" + }, + "application/vnd.futoin+json": { + source: "iana", + compressible: true + }, + "application/vnd.fuzzysheet": { + source: "iana", + extensions: [ + "fzs" + ] + }, + "application/vnd.genomatix.tuxedo": { + source: "iana", + extensions: [ + "txd" + ] + }, + "application/vnd.gentics.grd+json": { + source: "iana", + compressible: true + }, + "application/vnd.geo+json": { + source: "iana", + compressible: true + }, + "application/vnd.geocube+xml": { + source: "iana", + compressible: true + }, + "application/vnd.geogebra.file": { + source: "iana", + extensions: [ + "ggb" + ] + }, + "application/vnd.geogebra.slides": { + source: "iana" + }, + "application/vnd.geogebra.tool": { + source: "iana", + extensions: [ + "ggt" + ] + }, + "application/vnd.geometry-explorer": { + source: "iana", + extensions: [ + "gex", + "gre" + ] + }, + "application/vnd.geonext": { + source: "iana", + extensions: [ + "gxt" + ] + }, + "application/vnd.geoplan": { + source: "iana", + extensions: [ + "g2w" + ] + }, + "application/vnd.geospace": { + source: "iana", + extensions: [ + "g3w" + ] + }, + "application/vnd.gerber": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + source: "iana" + }, + "application/vnd.gmx": { + source: "iana", + extensions: [ + "gmx" + ] + }, + "application/vnd.google-apps.document": { + compressible: false, + extensions: [ + "gdoc" + ] + }, + "application/vnd.google-apps.presentation": { + compressible: false, + extensions: [ + "gslides" + ] + }, + "application/vnd.google-apps.spreadsheet": { + compressible: false, + extensions: [ + "gsheet" + ] + }, + "application/vnd.google-earth.kml+xml": { + source: "iana", + compressible: true, + extensions: [ + "kml" + ] + }, + "application/vnd.google-earth.kmz": { + source: "iana", + compressible: false, + extensions: [ + "kmz" + ] + }, + "application/vnd.gov.sk.e-form+xml": { + source: "iana", + compressible: true + }, + "application/vnd.gov.sk.e-form+zip": { + source: "iana", + compressible: false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.grafeq": { + source: "iana", + extensions: [ + "gqf", + "gqs" + ] + }, + "application/vnd.gridmp": { + source: "iana" + }, + "application/vnd.groove-account": { + source: "iana", + extensions: [ + "gac" + ] + }, + "application/vnd.groove-help": { + source: "iana", + extensions: [ + "ghf" + ] + }, + "application/vnd.groove-identity-message": { + source: "iana", + extensions: [ + "gim" + ] + }, + "application/vnd.groove-injector": { + source: "iana", + extensions: [ + "grv" + ] + }, + "application/vnd.groove-tool-message": { + source: "iana", + extensions: [ + "gtm" + ] + }, + "application/vnd.groove-tool-template": { + source: "iana", + extensions: [ + "tpl" + ] + }, + "application/vnd.groove-vcard": { + source: "iana", + extensions: [ + "vcg" + ] + }, + "application/vnd.hal+json": { + source: "iana", + compressible: true + }, + "application/vnd.hal+xml": { + source: "iana", + compressible: true, + extensions: [ + "hal" + ] + }, + "application/vnd.handheld-entertainment+xml": { + source: "iana", + compressible: true, + extensions: [ + "zmm" + ] + }, + "application/vnd.hbci": { + source: "iana", + extensions: [ + "hbci" + ] + }, + "application/vnd.hc+json": { + source: "iana", + compressible: true + }, + "application/vnd.hcl-bireports": { + source: "iana" + }, + "application/vnd.hdt": { + source: "iana" + }, + "application/vnd.heroku+json": { + source: "iana", + compressible: true + }, + "application/vnd.hhe.lesson-player": { + source: "iana", + extensions: [ + "les" + ] + }, + "application/vnd.hl7cda+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hl7v2+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hp-hpgl": { + source: "iana", + extensions: [ + "hpgl" + ] + }, + "application/vnd.hp-hpid": { + source: "iana", + extensions: [ + "hpid" + ] + }, + "application/vnd.hp-hps": { + source: "iana", + extensions: [ + "hps" + ] + }, + "application/vnd.hp-jlyt": { + source: "iana", + extensions: [ + "jlt" + ] + }, + "application/vnd.hp-pcl": { + source: "iana", + extensions: [ + "pcl" + ] + }, + "application/vnd.hp-pclxl": { + source: "iana", + extensions: [ + "pclxl" + ] + }, + "application/vnd.httphone": { + source: "iana" + }, + "application/vnd.hydrostatix.sof-data": { + source: "iana", + extensions: [ + "sfd-hdstx" + ] + }, + "application/vnd.hyper+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyper-item+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyperdrive+json": { + source: "iana", + compressible: true + }, + "application/vnd.hzn-3d-crossword": { + source: "iana" + }, + "application/vnd.ibm.afplinedata": { + source: "iana" + }, + "application/vnd.ibm.electronic-media": { + source: "iana" + }, + "application/vnd.ibm.minipay": { + source: "iana", + extensions: [ + "mpy" + ] + }, + "application/vnd.ibm.modcap": { + source: "iana", + extensions: [ + "afp", + "listafp", + "list3820" + ] + }, + "application/vnd.ibm.rights-management": { + source: "iana", + extensions: [ + "irm" + ] + }, + "application/vnd.ibm.secure-container": { + source: "iana", + extensions: [ + "sc" + ] + }, + "application/vnd.iccprofile": { + source: "iana", + extensions: [ + "icc", + "icm" + ] + }, + "application/vnd.ieee.1905": { + source: "iana" + }, + "application/vnd.igloader": { + source: "iana", + extensions: [ + "igl" + ] + }, + "application/vnd.imagemeter.folder+zip": { + source: "iana", + compressible: false + }, + "application/vnd.imagemeter.image+zip": { + source: "iana", + compressible: false + }, + "application/vnd.immervision-ivp": { + source: "iana", + extensions: [ + "ivp" + ] + }, + "application/vnd.immervision-ivu": { + source: "iana", + extensions: [ + "ivu" + ] + }, + "application/vnd.ims.imsccv1p1": { + source: "iana" + }, + "application/vnd.ims.imsccv1p2": { + source: "iana" + }, + "application/vnd.ims.imsccv1p3": { + source: "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + source: "iana", + compressible: true + }, + "application/vnd.informedcontrol.rms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.informix-visionary": { + source: "iana" + }, + "application/vnd.infotech.project": { + source: "iana" + }, + "application/vnd.infotech.project+xml": { + source: "iana", + compressible: true + }, + "application/vnd.innopath.wamp.notification": { + source: "iana" + }, + "application/vnd.insors.igm": { + source: "iana", + extensions: [ + "igm" + ] + }, + "application/vnd.intercon.formnet": { + source: "iana", + extensions: [ + "xpw", + "xpx" + ] + }, + "application/vnd.intergeo": { + source: "iana", + extensions: [ + "i2g" + ] + }, + "application/vnd.intertrust.digibox": { + source: "iana" + }, + "application/vnd.intertrust.nncp": { + source: "iana" + }, + "application/vnd.intu.qbo": { + source: "iana", + extensions: [ + "qbo" + ] + }, + "application/vnd.intu.qfx": { + source: "iana", + extensions: [ + "qfx" + ] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.packageitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.planningitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ipunplugged.rcprofile": { + source: "iana", + extensions: [ + "rcprofile" + ] + }, + "application/vnd.irepository.package+xml": { + source: "iana", + compressible: true, + extensions: [ + "irp" + ] + }, + "application/vnd.is-xpr": { + source: "iana", + extensions: [ + "xpr" + ] + }, + "application/vnd.isac.fcs": { + source: "iana", + extensions: [ + "fcs" + ] + }, + "application/vnd.iso11783-10+zip": { + source: "iana", + compressible: false + }, + "application/vnd.jam": { + source: "iana", + extensions: [ + "jam" + ] + }, + "application/vnd.japannet-directory-service": { + source: "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-payment-wakeup": { + source: "iana" + }, + "application/vnd.japannet-registration": { + source: "iana" + }, + "application/vnd.japannet-registration-wakeup": { + source: "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-verification": { + source: "iana" + }, + "application/vnd.japannet-verification-wakeup": { + source: "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + source: "iana", + extensions: [ + "rms" + ] + }, + "application/vnd.jisp": { + source: "iana", + extensions: [ + "jisp" + ] + }, + "application/vnd.joost.joda-archive": { + source: "iana", + extensions: [ + "joda" + ] + }, + "application/vnd.jsk.isdn-ngn": { + source: "iana" + }, + "application/vnd.kahootz": { + source: "iana", + extensions: [ + "ktz", + "ktr" + ] + }, + "application/vnd.kde.karbon": { + source: "iana", + extensions: [ + "karbon" + ] + }, + "application/vnd.kde.kchart": { + source: "iana", + extensions: [ + "chrt" + ] + }, + "application/vnd.kde.kformula": { + source: "iana", + extensions: [ + "kfo" + ] + }, + "application/vnd.kde.kivio": { + source: "iana", + extensions: [ + "flw" + ] + }, + "application/vnd.kde.kontour": { + source: "iana", + extensions: [ + "kon" + ] + }, + "application/vnd.kde.kpresenter": { + source: "iana", + extensions: [ + "kpr", + "kpt" + ] + }, + "application/vnd.kde.kspread": { + source: "iana", + extensions: [ + "ksp" + ] + }, + "application/vnd.kde.kword": { + source: "iana", + extensions: [ + "kwd", + "kwt" + ] + }, + "application/vnd.kenameaapp": { + source: "iana", + extensions: [ + "htke" + ] + }, + "application/vnd.kidspiration": { + source: "iana", + extensions: [ + "kia" + ] + }, + "application/vnd.kinar": { + source: "iana", + extensions: [ + "kne", + "knp" + ] + }, + "application/vnd.koan": { + source: "iana", + extensions: [ + "skp", + "skd", + "skt", + "skm" + ] + }, + "application/vnd.kodak-descriptor": { + source: "iana", + extensions: [ + "sse" + ] + }, + "application/vnd.las": { + source: "iana" + }, + "application/vnd.las.las+json": { + source: "iana", + compressible: true + }, + "application/vnd.las.las+xml": { + source: "iana", + compressible: true, + extensions: [ + "lasxml" + ] + }, + "application/vnd.laszip": { + source: "iana" + }, + "application/vnd.leap+json": { + source: "iana", + compressible: true + }, + "application/vnd.liberty-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + source: "iana", + extensions: [ + "lbd" + ] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + source: "iana", + compressible: true, + extensions: [ + "lbe" + ] + }, + "application/vnd.logipipe.circuit+zip": { + source: "iana", + compressible: false + }, + "application/vnd.loom": { + source: "iana" + }, + "application/vnd.lotus-1-2-3": { + source: "iana", + extensions: [ + "123" + ] + }, + "application/vnd.lotus-approach": { + source: "iana", + extensions: [ + "apr" + ] + }, + "application/vnd.lotus-freelance": { + source: "iana", + extensions: [ + "pre" + ] + }, + "application/vnd.lotus-notes": { + source: "iana", + extensions: [ + "nsf" + ] + }, + "application/vnd.lotus-organizer": { + source: "iana", + extensions: [ + "org" + ] + }, + "application/vnd.lotus-screencam": { + source: "iana", + extensions: [ + "scm" + ] + }, + "application/vnd.lotus-wordpro": { + source: "iana", + extensions: [ + "lwp" + ] + }, + "application/vnd.macports.portpkg": { + source: "iana", + extensions: [ + "portpkg" + ] + }, + "application/vnd.mapbox-vector-tile": { + source: "iana", + extensions: [ + "mvt" + ] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.conftoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.license+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.mdcf": { + source: "iana" + }, + "application/vnd.mason+json": { + source: "iana", + compressible: true + }, + "application/vnd.maxar.archive.3tz+zip": { + source: "iana", + compressible: false + }, + "application/vnd.maxmind.maxmind-db": { + source: "iana" + }, + "application/vnd.mcd": { + source: "iana", + extensions: [ + "mcd" + ] + }, + "application/vnd.medcalcdata": { + source: "iana", + extensions: [ + "mc1" + ] + }, + "application/vnd.mediastation.cdkey": { + source: "iana", + extensions: [ + "cdkey" + ] + }, + "application/vnd.meridian-slingshot": { + source: "iana" + }, + "application/vnd.mfer": { + source: "iana", + extensions: [ + "mwf" + ] + }, + "application/vnd.mfmp": { + source: "iana", + extensions: [ + "mfm" + ] + }, + "application/vnd.micro+json": { + source: "iana", + compressible: true + }, + "application/vnd.micrografx.flo": { + source: "iana", + extensions: [ + "flo" + ] + }, + "application/vnd.micrografx.igx": { + source: "iana", + extensions: [ + "igx" + ] + }, + "application/vnd.microsoft.portable-executable": { + source: "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + source: "iana" + }, + "application/vnd.miele+json": { + source: "iana", + compressible: true + }, + "application/vnd.mif": { + source: "iana", + extensions: [ + "mif" + ] + }, + "application/vnd.minisoft-hp3000-save": { + source: "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + source: "iana" + }, + "application/vnd.mobius.daf": { + source: "iana", + extensions: [ + "daf" + ] + }, + "application/vnd.mobius.dis": { + source: "iana", + extensions: [ + "dis" + ] + }, + "application/vnd.mobius.mbk": { + source: "iana", + extensions: [ + "mbk" + ] + }, + "application/vnd.mobius.mqy": { + source: "iana", + extensions: [ + "mqy" + ] + }, + "application/vnd.mobius.msl": { + source: "iana", + extensions: [ + "msl" + ] + }, + "application/vnd.mobius.plc": { + source: "iana", + extensions: [ + "plc" + ] + }, + "application/vnd.mobius.txf": { + source: "iana", + extensions: [ + "txf" + ] + }, + "application/vnd.mophun.application": { + source: "iana", + extensions: [ + "mpn" + ] + }, + "application/vnd.mophun.certificate": { + source: "iana", + extensions: [ + "mpc" + ] + }, + "application/vnd.motorola.flexsuite": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + source: "iana" + }, + "application/vnd.motorola.iprm": { + source: "iana" + }, + "application/vnd.mozilla.xul+xml": { + source: "iana", + compressible: true, + extensions: [ + "xul" + ] + }, + "application/vnd.ms-3mfdocument": { + source: "iana" + }, + "application/vnd.ms-artgalry": { + source: "iana", + extensions: [ + "cil" + ] + }, + "application/vnd.ms-asf": { + source: "iana" + }, + "application/vnd.ms-cab-compressed": { + source: "iana", + extensions: [ + "cab" + ] + }, + "application/vnd.ms-color.iccprofile": { + source: "apache" + }, + "application/vnd.ms-excel": { + source: "iana", + compressible: false, + extensions: [ + "xls", + "xlm", + "xla", + "xlc", + "xlt", + "xlw" + ] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + source: "iana", + extensions: [ + "xlam" + ] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + source: "iana", + extensions: [ + "xlsb" + ] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + source: "iana", + extensions: [ + "xlsm" + ] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + source: "iana", + extensions: [ + "xltm" + ] + }, + "application/vnd.ms-fontobject": { + source: "iana", + compressible: true, + extensions: [ + "eot" + ] + }, + "application/vnd.ms-htmlhelp": { + source: "iana", + extensions: [ + "chm" + ] + }, + "application/vnd.ms-ims": { + source: "iana", + extensions: [ + "ims" + ] + }, + "application/vnd.ms-lrm": { + source: "iana", + extensions: [ + "lrm" + ] + }, + "application/vnd.ms-office.activex+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-officetheme": { + source: "iana", + extensions: [ + "thmx" + ] + }, + "application/vnd.ms-opentype": { + source: "apache", + compressible: true + }, + "application/vnd.ms-outlook": { + compressible: false, + extensions: [ + "msg" + ] + }, + "application/vnd.ms-package.obfuscated-opentype": { + source: "apache" + }, + "application/vnd.ms-pki.seccat": { + source: "apache", + extensions: [ + "cat" + ] + }, + "application/vnd.ms-pki.stl": { + source: "apache", + extensions: [ + "stl" + ] + }, + "application/vnd.ms-playready.initiator+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-powerpoint": { + source: "iana", + compressible: false, + extensions: [ + "ppt", + "pps", + "pot" + ] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + source: "iana", + extensions: [ + "ppam" + ] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + source: "iana", + extensions: [ + "pptm" + ] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + source: "iana", + extensions: [ + "sldm" + ] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + source: "iana", + extensions: [ + "ppsm" + ] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + source: "iana", + extensions: [ + "potm" + ] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-printing.printticket+xml": { + source: "apache", + compressible: true + }, + "application/vnd.ms-printschematicket+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-project": { + source: "iana", + extensions: [ + "mpp", + "mpt" + ] + }, + "application/vnd.ms-tnef": { + source: "iana" + }, + "application/vnd.ms-windows.devicepairing": { + source: "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + source: "iana" + }, + "application/vnd.ms-windows.printerpairing": { + source: "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + source: "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + source: "iana", + extensions: [ + "docm" + ] + }, + "application/vnd.ms-word.template.macroenabled.12": { + source: "iana", + extensions: [ + "dotm" + ] + }, + "application/vnd.ms-works": { + source: "iana", + extensions: [ + "wps", + "wks", + "wcm", + "wdb" + ] + }, + "application/vnd.ms-wpl": { + source: "iana", + extensions: [ + "wpl" + ] + }, + "application/vnd.ms-xpsdocument": { + source: "iana", + compressible: false, + extensions: [ + "xps" + ] + }, + "application/vnd.msa-disk-image": { + source: "iana" + }, + "application/vnd.mseq": { + source: "iana", + extensions: [ + "mseq" + ] + }, + "application/vnd.msign": { + source: "iana" + }, + "application/vnd.multiad.creator": { + source: "iana" + }, + "application/vnd.multiad.creator.cif": { + source: "iana" + }, + "application/vnd.music-niff": { + source: "iana" + }, + "application/vnd.musician": { + source: "iana", + extensions: [ + "mus" + ] + }, + "application/vnd.muvee.style": { + source: "iana", + extensions: [ + "msty" + ] + }, + "application/vnd.mynfc": { + source: "iana", + extensions: [ + "taglet" + ] + }, + "application/vnd.nacamar.ybrid+json": { + source: "iana", + compressible: true + }, + "application/vnd.ncd.control": { + source: "iana" + }, + "application/vnd.ncd.reference": { + source: "iana" + }, + "application/vnd.nearst.inv+json": { + source: "iana", + compressible: true + }, + "application/vnd.nebumind.line": { + source: "iana" + }, + "application/vnd.nervana": { + source: "iana" + }, + "application/vnd.netfpx": { + source: "iana" + }, + "application/vnd.neurolanguage.nlu": { + source: "iana", + extensions: [ + "nlu" + ] + }, + "application/vnd.nimn": { + source: "iana" + }, + "application/vnd.nintendo.nitro.rom": { + source: "iana" + }, + "application/vnd.nintendo.snes.rom": { + source: "iana" + }, + "application/vnd.nitf": { + source: "iana", + extensions: [ + "ntf", + "nitf" + ] + }, + "application/vnd.noblenet-directory": { + source: "iana", + extensions: [ + "nnd" + ] + }, + "application/vnd.noblenet-sealer": { + source: "iana", + extensions: [ + "nns" + ] + }, + "application/vnd.noblenet-web": { + source: "iana", + extensions: [ + "nnw" + ] + }, + "application/vnd.nokia.catalogs": { + source: "iana" + }, + "application/vnd.nokia.conml+wbxml": { + source: "iana" + }, + "application/vnd.nokia.conml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.iptv.config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.isds-radio-presets": { + source: "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + source: "iana" + }, + "application/vnd.nokia.landmark+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.landmarkcollection+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.n-gage.ac+xml": { + source: "iana", + compressible: true, + extensions: [ + "ac" + ] + }, + "application/vnd.nokia.n-gage.data": { + source: "iana", + extensions: [ + "ngdat" + ] + }, + "application/vnd.nokia.n-gage.symbian.install": { + source: "iana", + extensions: [ + "n-gage" + ] + }, + "application/vnd.nokia.ncd": { + source: "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + source: "iana" + }, + "application/vnd.nokia.pcd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.radio-preset": { + source: "iana", + extensions: [ + "rpst" + ] + }, + "application/vnd.nokia.radio-presets": { + source: "iana", + extensions: [ + "rpss" + ] + }, + "application/vnd.novadigm.edm": { + source: "iana", + extensions: [ + "edm" + ] + }, + "application/vnd.novadigm.edx": { + source: "iana", + extensions: [ + "edx" + ] + }, + "application/vnd.novadigm.ext": { + source: "iana", + extensions: [ + "ext" + ] + }, + "application/vnd.ntt-local.content-share": { + source: "iana" + }, + "application/vnd.ntt-local.file-transfer": { + source: "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + source: "iana" + }, + "application/vnd.oasis.opendocument.chart": { + source: "iana", + extensions: [ + "odc" + ] + }, + "application/vnd.oasis.opendocument.chart-template": { + source: "iana", + extensions: [ + "otc" + ] + }, + "application/vnd.oasis.opendocument.database": { + source: "iana", + extensions: [ + "odb" + ] + }, + "application/vnd.oasis.opendocument.formula": { + source: "iana", + extensions: [ + "odf" + ] + }, + "application/vnd.oasis.opendocument.formula-template": { + source: "iana", + extensions: [ + "odft" + ] + }, + "application/vnd.oasis.opendocument.graphics": { + source: "iana", + compressible: false, + extensions: [ + "odg" + ] + }, + "application/vnd.oasis.opendocument.graphics-template": { + source: "iana", + extensions: [ + "otg" + ] + }, + "application/vnd.oasis.opendocument.image": { + source: "iana", + extensions: [ + "odi" + ] + }, + "application/vnd.oasis.opendocument.image-template": { + source: "iana", + extensions: [ + "oti" + ] + }, + "application/vnd.oasis.opendocument.presentation": { + source: "iana", + compressible: false, + extensions: [ + "odp" + ] + }, + "application/vnd.oasis.opendocument.presentation-template": { + source: "iana", + extensions: [ + "otp" + ] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + source: "iana", + compressible: false, + extensions: [ + "ods" + ] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + source: "iana", + extensions: [ + "ots" + ] + }, + "application/vnd.oasis.opendocument.text": { + source: "iana", + compressible: false, + extensions: [ + "odt" + ] + }, + "application/vnd.oasis.opendocument.text-master": { + source: "iana", + extensions: [ + "odm" + ] + }, + "application/vnd.oasis.opendocument.text-template": { + source: "iana", + extensions: [ + "ott" + ] + }, + "application/vnd.oasis.opendocument.text-web": { + source: "iana", + extensions: [ + "oth" + ] + }, + "application/vnd.obn": { + source: "iana" + }, + "application/vnd.ocf+cbor": { + source: "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + source: "iana", + compressible: true + }, + "application/vnd.oftn.l10n+json": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.cspg-hexbinary": { + source: "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.dae.xhtml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.pae.gem": { + source: "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.spdlist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.ueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.userprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.olpc-sugar": { + source: "iana", + extensions: [ + "xo" + ] + }, + "application/vnd.oma-scws-config": { + source: "iana" + }, + "application/vnd.oma-scws-http-request": { + source: "iana" + }, + "application/vnd.oma-scws-http-response": { + source: "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.imd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.ltkm": { + source: "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + source: "iana" + }, + "application/vnd.oma.bcast.sgboot": { + source: "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sgdu": { + source: "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + source: "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sprov+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.stkm": { + source: "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-feature-handler+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-pcc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-subs-invite+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-user-prefs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.dcd": { + source: "iana" + }, + "application/vnd.oma.dcdc": { + source: "iana" + }, + "application/vnd.oma.dd2+xml": { + source: "iana", + compressible: true, + extensions: [ + "dd2" + ] + }, + "application/vnd.oma.drm.risd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.group-usage-list+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+cbor": { + source: "iana" + }, + "application/vnd.oma.lwm2m+json": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+tlv": { + source: "iana" + }, + "application/vnd.oma.pal+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.final-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.groups+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.push": { + source: "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.xcap-directory+xml": { + source: "iana", + compressible: true + }, + "application/vnd.omads-email+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-file+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-folder+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omaloc-supl-init": { + source: "iana" + }, + "application/vnd.onepager": { + source: "iana" + }, + "application/vnd.onepagertamp": { + source: "iana" + }, + "application/vnd.onepagertamx": { + source: "iana" + }, + "application/vnd.onepagertat": { + source: "iana" + }, + "application/vnd.onepagertatp": { + source: "iana" + }, + "application/vnd.onepagertatx": { + source: "iana" + }, + "application/vnd.openblox.game+xml": { + source: "iana", + compressible: true, + extensions: [ + "obgx" + ] + }, + "application/vnd.openblox.game-binary": { + source: "iana" + }, + "application/vnd.openeye.oeb": { + source: "iana" + }, + "application/vnd.openofficeorg.extension": { + source: "apache", + extensions: [ + "oxt" + ] + }, + "application/vnd.openstreetmap.data+xml": { + source: "iana", + compressible: true, + extensions: [ + "osm" + ] + }, + "application/vnd.opentimestamps.ots": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + source: "iana", + compressible: false, + extensions: [ + "pptx" + ] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + source: "iana", + extensions: [ + "sldx" + ] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + source: "iana", + extensions: [ + "ppsx" + ] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + source: "iana", + extensions: [ + "potx" + ] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + source: "iana", + compressible: false, + extensions: [ + "xlsx" + ] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + source: "iana", + extensions: [ + "xltx" + ] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + source: "iana", + compressible: false, + extensions: [ + "docx" + ] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + source: "iana", + extensions: [ + "dotx" + ] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oracle.resource+json": { + source: "iana", + compressible: true + }, + "application/vnd.orange.indata": { + source: "iana" + }, + "application/vnd.osa.netdeploy": { + source: "iana" + }, + "application/vnd.osgeo.mapguide.package": { + source: "iana", + extensions: [ + "mgp" + ] + }, + "application/vnd.osgi.bundle": { + source: "iana" + }, + "application/vnd.osgi.dp": { + source: "iana", + extensions: [ + "dp" + ] + }, + "application/vnd.osgi.subsystem": { + source: "iana", + extensions: [ + "esa" + ] + }, + "application/vnd.otps.ct-kip+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oxli.countgraph": { + source: "iana" + }, + "application/vnd.pagerduty+json": { + source: "iana", + compressible: true + }, + "application/vnd.palm": { + source: "iana", + extensions: [ + "pdb", + "pqa", + "oprc" + ] + }, + "application/vnd.panoply": { + source: "iana" + }, + "application/vnd.paos.xml": { + source: "iana" + }, + "application/vnd.patentdive": { + source: "iana" + }, + "application/vnd.patientecommsdoc": { + source: "iana" + }, + "application/vnd.pawaafile": { + source: "iana", + extensions: [ + "paw" + ] + }, + "application/vnd.pcos": { + source: "iana" + }, + "application/vnd.pg.format": { + source: "iana", + extensions: [ + "str" + ] + }, + "application/vnd.pg.osasli": { + source: "iana", + extensions: [ + "ei6" + ] + }, + "application/vnd.piaccess.application-licence": { + source: "iana" + }, + "application/vnd.picsel": { + source: "iana", + extensions: [ + "efif" + ] + }, + "application/vnd.pmi.widget": { + source: "iana", + extensions: [ + "wg" + ] + }, + "application/vnd.poc.group-advertisement+xml": { + source: "iana", + compressible: true + }, + "application/vnd.pocketlearn": { + source: "iana", + extensions: [ + "plf" + ] + }, + "application/vnd.powerbuilder6": { + source: "iana", + extensions: [ + "pbd" + ] + }, + "application/vnd.powerbuilder6-s": { + source: "iana" + }, + "application/vnd.powerbuilder7": { + source: "iana" + }, + "application/vnd.powerbuilder7-s": { + source: "iana" + }, + "application/vnd.powerbuilder75": { + source: "iana" + }, + "application/vnd.powerbuilder75-s": { + source: "iana" + }, + "application/vnd.preminet": { + source: "iana" + }, + "application/vnd.previewsystems.box": { + source: "iana", + extensions: [ + "box" + ] + }, + "application/vnd.proteus.magazine": { + source: "iana", + extensions: [ + "mgz" + ] + }, + "application/vnd.psfs": { + source: "iana" + }, + "application/vnd.publishare-delta-tree": { + source: "iana", + extensions: [ + "qps" + ] + }, + "application/vnd.pvi.ptid1": { + source: "iana", + extensions: [ + "ptid" + ] + }, + "application/vnd.pwg-multiplexed": { + source: "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + source: "iana", + compressible: true + }, + "application/vnd.qualcomm.brew-app-res": { + source: "iana" + }, + "application/vnd.quarantainenet": { + source: "iana" + }, + "application/vnd.quark.quarkxpress": { + source: "iana", + extensions: [ + "qxd", + "qxt", + "qwd", + "qwt", + "qxl", + "qxb" + ] + }, + "application/vnd.quobject-quoxdocument": { + source: "iana" + }, + "application/vnd.radisys.moml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + source: "iana", + compressible: true + }, + "application/vnd.rainstor.data": { + source: "iana" + }, + "application/vnd.rapid": { + source: "iana" + }, + "application/vnd.rar": { + source: "iana", + extensions: [ + "rar" + ] + }, + "application/vnd.realvnc.bed": { + source: "iana", + extensions: [ + "bed" + ] + }, + "application/vnd.recordare.musicxml": { + source: "iana", + extensions: [ + "mxl" + ] + }, + "application/vnd.recordare.musicxml+xml": { + source: "iana", + compressible: true, + extensions: [ + "musicxml" + ] + }, + "application/vnd.renlearn.rlprint": { + source: "iana" + }, + "application/vnd.resilient.logic": { + source: "iana" + }, + "application/vnd.restful+json": { + source: "iana", + compressible: true + }, + "application/vnd.rig.cryptonote": { + source: "iana", + extensions: [ + "cryptonote" + ] + }, + "application/vnd.rim.cod": { + source: "apache", + extensions: [ + "cod" + ] + }, + "application/vnd.rn-realmedia": { + source: "apache", + extensions: [ + "rm" + ] + }, + "application/vnd.rn-realmedia-vbr": { + source: "apache", + extensions: [ + "rmvb" + ] + }, + "application/vnd.route66.link66+xml": { + source: "iana", + compressible: true, + extensions: [ + "link66" + ] + }, + "application/vnd.rs-274x": { + source: "iana" + }, + "application/vnd.ruckus.download": { + source: "iana" + }, + "application/vnd.s3sms": { + source: "iana" + }, + "application/vnd.sailingtracker.track": { + source: "iana", + extensions: [ + "st" + ] + }, + "application/vnd.sar": { + source: "iana" + }, + "application/vnd.sbm.cid": { + source: "iana" + }, + "application/vnd.sbm.mid2": { + source: "iana" + }, + "application/vnd.scribus": { + source: "iana" + }, + "application/vnd.sealed.3df": { + source: "iana" + }, + "application/vnd.sealed.csf": { + source: "iana" + }, + "application/vnd.sealed.doc": { + source: "iana" + }, + "application/vnd.sealed.eml": { + source: "iana" + }, + "application/vnd.sealed.mht": { + source: "iana" + }, + "application/vnd.sealed.net": { + source: "iana" + }, + "application/vnd.sealed.ppt": { + source: "iana" + }, + "application/vnd.sealed.tiff": { + source: "iana" + }, + "application/vnd.sealed.xls": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + source: "iana" + }, + "application/vnd.seemail": { + source: "iana", + extensions: [ + "see" + ] + }, + "application/vnd.seis+json": { + source: "iana", + compressible: true + }, + "application/vnd.sema": { + source: "iana", + extensions: [ + "sema" + ] + }, + "application/vnd.semd": { + source: "iana", + extensions: [ + "semd" + ] + }, + "application/vnd.semf": { + source: "iana", + extensions: [ + "semf" + ] + }, + "application/vnd.shade-save-file": { + source: "iana" + }, + "application/vnd.shana.informed.formdata": { + source: "iana", + extensions: [ + "ifm" + ] + }, + "application/vnd.shana.informed.formtemplate": { + source: "iana", + extensions: [ + "itp" + ] + }, + "application/vnd.shana.informed.interchange": { + source: "iana", + extensions: [ + "iif" + ] + }, + "application/vnd.shana.informed.package": { + source: "iana", + extensions: [ + "ipk" + ] + }, + "application/vnd.shootproof+json": { + source: "iana", + compressible: true + }, + "application/vnd.shopkick+json": { + source: "iana", + compressible: true + }, + "application/vnd.shp": { + source: "iana" + }, + "application/vnd.shx": { + source: "iana" + }, + "application/vnd.sigrok.session": { + source: "iana" + }, + "application/vnd.simtech-mindmapper": { + source: "iana", + extensions: [ + "twd", + "twds" + ] + }, + "application/vnd.siren+json": { + source: "iana", + compressible: true + }, + "application/vnd.smaf": { + source: "iana", + extensions: [ + "mmf" + ] + }, + "application/vnd.smart.notebook": { + source: "iana" + }, + "application/vnd.smart.teacher": { + source: "iana", + extensions: [ + "teacher" + ] + }, + "application/vnd.snesdev-page-table": { + source: "iana" + }, + "application/vnd.software602.filler.form+xml": { + source: "iana", + compressible: true, + extensions: [ + "fo" + ] + }, + "application/vnd.software602.filler.form-xml-zip": { + source: "iana" + }, + "application/vnd.solent.sdkm+xml": { + source: "iana", + compressible: true, + extensions: [ + "sdkm", + "sdkd" + ] + }, + "application/vnd.spotfire.dxp": { + source: "iana", + extensions: [ + "dxp" + ] + }, + "application/vnd.spotfire.sfs": { + source: "iana", + extensions: [ + "sfs" + ] + }, + "application/vnd.sqlite3": { + source: "iana" + }, + "application/vnd.sss-cod": { + source: "iana" + }, + "application/vnd.sss-dtf": { + source: "iana" + }, + "application/vnd.sss-ntf": { + source: "iana" + }, + "application/vnd.stardivision.calc": { + source: "apache", + extensions: [ + "sdc" + ] + }, + "application/vnd.stardivision.draw": { + source: "apache", + extensions: [ + "sda" + ] + }, + "application/vnd.stardivision.impress": { + source: "apache", + extensions: [ + "sdd" + ] + }, + "application/vnd.stardivision.math": { + source: "apache", + extensions: [ + "smf" + ] + }, + "application/vnd.stardivision.writer": { + source: "apache", + extensions: [ + "sdw", + "vor" + ] + }, + "application/vnd.stardivision.writer-global": { + source: "apache", + extensions: [ + "sgl" + ] + }, + "application/vnd.stepmania.package": { + source: "iana", + extensions: [ + "smzip" + ] + }, + "application/vnd.stepmania.stepchart": { + source: "iana", + extensions: [ + "sm" + ] + }, + "application/vnd.street-stream": { + source: "iana" + }, + "application/vnd.sun.wadl+xml": { + source: "iana", + compressible: true, + extensions: [ + "wadl" + ] + }, + "application/vnd.sun.xml.calc": { + source: "apache", + extensions: [ + "sxc" + ] + }, + "application/vnd.sun.xml.calc.template": { + source: "apache", + extensions: [ + "stc" + ] + }, + "application/vnd.sun.xml.draw": { + source: "apache", + extensions: [ + "sxd" + ] + }, + "application/vnd.sun.xml.draw.template": { + source: "apache", + extensions: [ + "std" + ] + }, + "application/vnd.sun.xml.impress": { + source: "apache", + extensions: [ + "sxi" + ] + }, + "application/vnd.sun.xml.impress.template": { + source: "apache", + extensions: [ + "sti" + ] + }, + "application/vnd.sun.xml.math": { + source: "apache", + extensions: [ + "sxm" + ] + }, + "application/vnd.sun.xml.writer": { + source: "apache", + extensions: [ + "sxw" + ] + }, + "application/vnd.sun.xml.writer.global": { + source: "apache", + extensions: [ + "sxg" + ] + }, + "application/vnd.sun.xml.writer.template": { + source: "apache", + extensions: [ + "stw" + ] + }, + "application/vnd.sus-calendar": { + source: "iana", + extensions: [ + "sus", + "susp" + ] + }, + "application/vnd.svd": { + source: "iana", + extensions: [ + "svd" + ] + }, + "application/vnd.swiftview-ics": { + source: "iana" + }, + "application/vnd.sycle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.syft+json": { + source: "iana", + compressible: true + }, + "application/vnd.symbian.install": { + source: "apache", + extensions: [ + "sis", + "sisx" + ] + }, + "application/vnd.syncml+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "xsm" + ] + }, + "application/vnd.syncml.dm+wbxml": { + source: "iana", + charset: "UTF-8", + extensions: [ + "bdm" + ] + }, + "application/vnd.syncml.dm+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "xdm" + ] + }, + "application/vnd.syncml.dm.notification": { + source: "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmddf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "ddf" + ] + }, + "application/vnd.syncml.dmtnds+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.syncml.ds.notification": { + source: "iana" + }, + "application/vnd.tableschema+json": { + source: "iana", + compressible: true + }, + "application/vnd.tao.intent-module-archive": { + source: "iana", + extensions: [ + "tao" + ] + }, + "application/vnd.tcpdump.pcap": { + source: "iana", + extensions: [ + "pcap", + "cap", + "dmp" + ] + }, + "application/vnd.think-cell.ppttc+json": { + source: "iana", + compressible: true + }, + "application/vnd.tmd.mediaflex.api+xml": { + source: "iana", + compressible: true + }, + "application/vnd.tml": { + source: "iana" + }, + "application/vnd.tmobile-livetv": { + source: "iana", + extensions: [ + "tmo" + ] + }, + "application/vnd.tri.onesource": { + source: "iana" + }, + "application/vnd.trid.tpt": { + source: "iana", + extensions: [ + "tpt" + ] + }, + "application/vnd.triscape.mxs": { + source: "iana", + extensions: [ + "mxs" + ] + }, + "application/vnd.trueapp": { + source: "iana", + extensions: [ + "tra" + ] + }, + "application/vnd.truedoc": { + source: "iana" + }, + "application/vnd.ubisoft.webplayer": { + source: "iana" + }, + "application/vnd.ufdl": { + source: "iana", + extensions: [ + "ufd", + "ufdl" + ] + }, + "application/vnd.uiq.theme": { + source: "iana", + extensions: [ + "utz" + ] + }, + "application/vnd.umajin": { + source: "iana", + extensions: [ + "umj" + ] + }, + "application/vnd.unity": { + source: "iana", + extensions: [ + "unityweb" + ] + }, + "application/vnd.uoml+xml": { + source: "iana", + compressible: true, + extensions: [ + "uoml" + ] + }, + "application/vnd.uplanet.alert": { + source: "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.cacheop": { + source: "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.channel": { + source: "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.list": { + source: "iana" + }, + "application/vnd.uplanet.list-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.listcmd": { + source: "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.signal": { + source: "iana" + }, + "application/vnd.uri-map": { + source: "iana" + }, + "application/vnd.valve.source.material": { + source: "iana" + }, + "application/vnd.vcx": { + source: "iana", + extensions: [ + "vcx" + ] + }, + "application/vnd.vd-study": { + source: "iana" + }, + "application/vnd.vectorworks": { + source: "iana" + }, + "application/vnd.vel+json": { + source: "iana", + compressible: true + }, + "application/vnd.verimatrix.vcas": { + source: "iana" + }, + "application/vnd.veritone.aion+json": { + source: "iana", + compressible: true + }, + "application/vnd.veryant.thin": { + source: "iana" + }, + "application/vnd.ves.encrypted": { + source: "iana" + }, + "application/vnd.vidsoft.vidconference": { + source: "iana" + }, + "application/vnd.visio": { + source: "iana", + extensions: [ + "vsd", + "vst", + "vss", + "vsw" + ] + }, + "application/vnd.visionary": { + source: "iana", + extensions: [ + "vis" + ] + }, + "application/vnd.vividence.scriptfile": { + source: "iana" + }, + "application/vnd.vsf": { + source: "iana", + extensions: [ + "vsf" + ] + }, + "application/vnd.wap.sic": { + source: "iana" + }, + "application/vnd.wap.slc": { + source: "iana" + }, + "application/vnd.wap.wbxml": { + source: "iana", + charset: "UTF-8", + extensions: [ + "wbxml" + ] + }, + "application/vnd.wap.wmlc": { + source: "iana", + extensions: [ + "wmlc" + ] + }, + "application/vnd.wap.wmlscriptc": { + source: "iana", + extensions: [ + "wmlsc" + ] + }, + "application/vnd.webturbo": { + source: "iana", + extensions: [ + "wtb" + ] + }, + "application/vnd.wfa.dpp": { + source: "iana" + }, + "application/vnd.wfa.p2p": { + source: "iana" + }, + "application/vnd.wfa.wsc": { + source: "iana" + }, + "application/vnd.windows.devicepairing": { + source: "iana" + }, + "application/vnd.wmc": { + source: "iana" + }, + "application/vnd.wmf.bootstrap": { + source: "iana" + }, + "application/vnd.wolfram.mathematica": { + source: "iana" + }, + "application/vnd.wolfram.mathematica.package": { + source: "iana" + }, + "application/vnd.wolfram.player": { + source: "iana", + extensions: [ + "nbp" + ] + }, + "application/vnd.wordperfect": { + source: "iana", + extensions: [ + "wpd" + ] + }, + "application/vnd.wqd": { + source: "iana", + extensions: [ + "wqd" + ] + }, + "application/vnd.wrq-hp3000-labelled": { + source: "iana" + }, + "application/vnd.wt.stf": { + source: "iana", + extensions: [ + "stf" + ] + }, + "application/vnd.wv.csp+wbxml": { + source: "iana" + }, + "application/vnd.wv.csp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.wv.ssp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xacml+json": { + source: "iana", + compressible: true + }, + "application/vnd.xara": { + source: "iana", + extensions: [ + "xar" + ] + }, + "application/vnd.xfdl": { + source: "iana", + extensions: [ + "xfdl" + ] + }, + "application/vnd.xfdl.webform": { + source: "iana" + }, + "application/vnd.xmi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xmpie.cpkg": { + source: "iana" + }, + "application/vnd.xmpie.dpkg": { + source: "iana" + }, + "application/vnd.xmpie.plan": { + source: "iana" + }, + "application/vnd.xmpie.ppkg": { + source: "iana" + }, + "application/vnd.xmpie.xlim": { + source: "iana" + }, + "application/vnd.yamaha.hv-dic": { + source: "iana", + extensions: [ + "hvd" + ] + }, + "application/vnd.yamaha.hv-script": { + source: "iana", + extensions: [ + "hvs" + ] + }, + "application/vnd.yamaha.hv-voice": { + source: "iana", + extensions: [ + "hvp" + ] + }, + "application/vnd.yamaha.openscoreformat": { + source: "iana", + extensions: [ + "osf" + ] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + source: "iana", + compressible: true, + extensions: [ + "osfpvg" + ] + }, + "application/vnd.yamaha.remote-setup": { + source: "iana" + }, + "application/vnd.yamaha.smaf-audio": { + source: "iana", + extensions: [ + "saf" + ] + }, + "application/vnd.yamaha.smaf-phrase": { + source: "iana", + extensions: [ + "spf" + ] + }, + "application/vnd.yamaha.through-ngn": { + source: "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + source: "iana" + }, + "application/vnd.yaoweme": { + source: "iana" + }, + "application/vnd.yellowriver-custom-menu": { + source: "iana", + extensions: [ + "cmp" + ] + }, + "application/vnd.youtube.yt": { + source: "iana" + }, + "application/vnd.zul": { + source: "iana", + extensions: [ + "zir", + "zirz" + ] + }, + "application/vnd.zzazz.deck+xml": { + source: "iana", + compressible: true, + extensions: [ + "zaz" + ] + }, + "application/voicexml+xml": { + source: "iana", + compressible: true, + extensions: [ + "vxml" + ] + }, + "application/voucher-cms+json": { + source: "iana", + compressible: true + }, + "application/vq-rtcpxr": { + source: "iana" + }, + "application/wasm": { + source: "iana", + compressible: true, + extensions: [ + "wasm" + ] + }, + "application/watcherinfo+xml": { + source: "iana", + compressible: true, + extensions: [ + "wif" + ] + }, + "application/webpush-options+json": { + source: "iana", + compressible: true + }, + "application/whoispp-query": { + source: "iana" + }, + "application/whoispp-response": { + source: "iana" + }, + "application/widget": { + source: "iana", + extensions: [ + "wgt" + ] + }, + "application/winhlp": { + source: "apache", + extensions: [ + "hlp" + ] + }, + "application/wita": { + source: "iana" + }, + "application/wordperfect5.1": { + source: "iana" + }, + "application/wsdl+xml": { + source: "iana", + compressible: true, + extensions: [ + "wsdl" + ] + }, + "application/wspolicy+xml": { + source: "iana", + compressible: true, + extensions: [ + "wspolicy" + ] + }, + "application/x-7z-compressed": { + source: "apache", + compressible: false, + extensions: [ + "7z" + ] + }, + "application/x-abiword": { + source: "apache", + extensions: [ + "abw" + ] + }, + "application/x-ace-compressed": { + source: "apache", + extensions: [ + "ace" + ] + }, + "application/x-amf": { + source: "apache" + }, + "application/x-apple-diskimage": { + source: "apache", + extensions: [ + "dmg" + ] + }, + "application/x-arj": { + compressible: false, + extensions: [ + "arj" + ] + }, + "application/x-authorware-bin": { + source: "apache", + extensions: [ + "aab", + "x32", + "u32", + "vox" + ] + }, + "application/x-authorware-map": { + source: "apache", + extensions: [ + "aam" + ] + }, + "application/x-authorware-seg": { + source: "apache", + extensions: [ + "aas" + ] + }, + "application/x-bcpio": { + source: "apache", + extensions: [ + "bcpio" + ] + }, + "application/x-bdoc": { + compressible: false, + extensions: [ + "bdoc" + ] + }, + "application/x-bittorrent": { + source: "apache", + extensions: [ + "torrent" + ] + }, + "application/x-blorb": { + source: "apache", + extensions: [ + "blb", + "blorb" + ] + }, + "application/x-bzip": { + source: "apache", + compressible: false, + extensions: [ + "bz" + ] + }, + "application/x-bzip2": { + source: "apache", + compressible: false, + extensions: [ + "bz2", + "boz" + ] + }, + "application/x-cbr": { + source: "apache", + extensions: [ + "cbr", + "cba", + "cbt", + "cbz", + "cb7" + ] + }, + "application/x-cdlink": { + source: "apache", + extensions: [ + "vcd" + ] + }, + "application/x-cfs-compressed": { + source: "apache", + extensions: [ + "cfs" + ] + }, + "application/x-chat": { + source: "apache", + extensions: [ + "chat" + ] + }, + "application/x-chess-pgn": { + source: "apache", + extensions: [ + "pgn" + ] + }, + "application/x-chrome-extension": { + extensions: [ + "crx" + ] + }, + "application/x-cocoa": { + source: "nginx", + extensions: [ + "cco" + ] + }, + "application/x-compress": { + source: "apache" + }, + "application/x-conference": { + source: "apache", + extensions: [ + "nsc" + ] + }, + "application/x-cpio": { + source: "apache", + extensions: [ + "cpio" + ] + }, + "application/x-csh": { + source: "apache", + extensions: [ + "csh" + ] + }, + "application/x-deb": { + compressible: false + }, + "application/x-debian-package": { + source: "apache", + extensions: [ + "deb", + "udeb" + ] + }, + "application/x-dgc-compressed": { + source: "apache", + extensions: [ + "dgc" + ] + }, + "application/x-director": { + source: "apache", + extensions: [ + "dir", + "dcr", + "dxr", + "cst", + "cct", + "cxt", + "w3d", + "fgd", + "swa" + ] + }, + "application/x-doom": { + source: "apache", + extensions: [ + "wad" + ] + }, + "application/x-dtbncx+xml": { + source: "apache", + compressible: true, + extensions: [ + "ncx" + ] + }, + "application/x-dtbook+xml": { + source: "apache", + compressible: true, + extensions: [ + "dtb" + ] + }, + "application/x-dtbresource+xml": { + source: "apache", + compressible: true, + extensions: [ + "res" + ] + }, + "application/x-dvi": { + source: "apache", + compressible: false, + extensions: [ + "dvi" + ] + }, + "application/x-envoy": { + source: "apache", + extensions: [ + "evy" + ] + }, + "application/x-eva": { + source: "apache", + extensions: [ + "eva" + ] + }, + "application/x-font-bdf": { + source: "apache", + extensions: [ + "bdf" + ] + }, + "application/x-font-dos": { + source: "apache" + }, + "application/x-font-framemaker": { + source: "apache" + }, + "application/x-font-ghostscript": { + source: "apache", + extensions: [ + "gsf" + ] + }, + "application/x-font-libgrx": { + source: "apache" + }, + "application/x-font-linux-psf": { + source: "apache", + extensions: [ + "psf" + ] + }, + "application/x-font-pcf": { + source: "apache", + extensions: [ + "pcf" + ] + }, + "application/x-font-snf": { + source: "apache", + extensions: [ + "snf" + ] + }, + "application/x-font-speedo": { + source: "apache" + }, + "application/x-font-sunos-news": { + source: "apache" + }, + "application/x-font-type1": { + source: "apache", + extensions: [ + "pfa", + "pfb", + "pfm", + "afm" + ] + }, + "application/x-font-vfont": { + source: "apache" + }, + "application/x-freearc": { + source: "apache", + extensions: [ + "arc" + ] + }, + "application/x-futuresplash": { + source: "apache", + extensions: [ + "spl" + ] + }, + "application/x-gca-compressed": { + source: "apache", + extensions: [ + "gca" + ] + }, + "application/x-glulx": { + source: "apache", + extensions: [ + "ulx" + ] + }, + "application/x-gnumeric": { + source: "apache", + extensions: [ + "gnumeric" + ] + }, + "application/x-gramps-xml": { + source: "apache", + extensions: [ + "gramps" + ] + }, + "application/x-gtar": { + source: "apache", + extensions: [ + "gtar" + ] + }, + "application/x-gzip": { + source: "apache" + }, + "application/x-hdf": { + source: "apache", + extensions: [ + "hdf" + ] + }, + "application/x-httpd-php": { + compressible: true, + extensions: [ + "php" + ] + }, + "application/x-install-instructions": { + source: "apache", + extensions: [ + "install" + ] + }, + "application/x-iso9660-image": { + source: "apache", + extensions: [ + "iso" + ] + }, + "application/x-iwork-keynote-sffkey": { + extensions: [ + "key" + ] + }, + "application/x-iwork-numbers-sffnumbers": { + extensions: [ + "numbers" + ] + }, + "application/x-iwork-pages-sffpages": { + extensions: [ + "pages" + ] + }, + "application/x-java-archive-diff": { + source: "nginx", + extensions: [ + "jardiff" + ] + }, + "application/x-java-jnlp-file": { + source: "apache", + compressible: false, + extensions: [ + "jnlp" + ] + }, + "application/x-javascript": { + compressible: true + }, + "application/x-keepass2": { + extensions: [ + "kdbx" + ] + }, + "application/x-latex": { + source: "apache", + compressible: false, + extensions: [ + "latex" + ] + }, + "application/x-lua-bytecode": { + extensions: [ + "luac" + ] + }, + "application/x-lzh-compressed": { + source: "apache", + extensions: [ + "lzh", + "lha" + ] + }, + "application/x-makeself": { + source: "nginx", + extensions: [ + "run" + ] + }, + "application/x-mie": { + source: "apache", + extensions: [ + "mie" + ] + }, + "application/x-mobipocket-ebook": { + source: "apache", + extensions: [ + "prc", + "mobi" + ] + }, + "application/x-mpegurl": { + compressible: false + }, + "application/x-ms-application": { + source: "apache", + extensions: [ + "application" + ] + }, + "application/x-ms-shortcut": { + source: "apache", + extensions: [ + "lnk" + ] + }, + "application/x-ms-wmd": { + source: "apache", + extensions: [ + "wmd" + ] + }, + "application/x-ms-wmz": { + source: "apache", + extensions: [ + "wmz" + ] + }, + "application/x-ms-xbap": { + source: "apache", + extensions: [ + "xbap" + ] + }, + "application/x-msaccess": { + source: "apache", + extensions: [ + "mdb" + ] + }, + "application/x-msbinder": { + source: "apache", + extensions: [ + "obd" + ] + }, + "application/x-mscardfile": { + source: "apache", + extensions: [ + "crd" + ] + }, + "application/x-msclip": { + source: "apache", + extensions: [ + "clp" + ] + }, + "application/x-msdos-program": { + extensions: [ + "exe" + ] + }, + "application/x-msdownload": { + source: "apache", + extensions: [ + "exe", + "dll", + "com", + "bat", + "msi" + ] + }, + "application/x-msmediaview": { + source: "apache", + extensions: [ + "mvb", + "m13", + "m14" + ] + }, + "application/x-msmetafile": { + source: "apache", + extensions: [ + "wmf", + "wmz", + "emf", + "emz" + ] + }, + "application/x-msmoney": { + source: "apache", + extensions: [ + "mny" + ] + }, + "application/x-mspublisher": { + source: "apache", + extensions: [ + "pub" + ] + }, + "application/x-msschedule": { + source: "apache", + extensions: [ + "scd" + ] + }, + "application/x-msterminal": { + source: "apache", + extensions: [ + "trm" + ] + }, + "application/x-mswrite": { + source: "apache", + extensions: [ + "wri" + ] + }, + "application/x-netcdf": { + source: "apache", + extensions: [ + "nc", + "cdf" + ] + }, + "application/x-ns-proxy-autoconfig": { + compressible: true, + extensions: [ + "pac" + ] + }, + "application/x-nzb": { + source: "apache", + extensions: [ + "nzb" + ] + }, + "application/x-perl": { + source: "nginx", + extensions: [ + "pl", + "pm" + ] + }, + "application/x-pilot": { + source: "nginx", + extensions: [ + "prc", + "pdb" + ] + }, + "application/x-pkcs12": { + source: "apache", + compressible: false, + extensions: [ + "p12", + "pfx" + ] + }, + "application/x-pkcs7-certificates": { + source: "apache", + extensions: [ + "p7b", + "spc" + ] + }, + "application/x-pkcs7-certreqresp": { + source: "apache", + extensions: [ + "p7r" + ] + }, + "application/x-pki-message": { + source: "iana" + }, + "application/x-rar-compressed": { + source: "apache", + compressible: false, + extensions: [ + "rar" + ] + }, + "application/x-redhat-package-manager": { + source: "nginx", + extensions: [ + "rpm" + ] + }, + "application/x-research-info-systems": { + source: "apache", + extensions: [ + "ris" + ] + }, + "application/x-sea": { + source: "nginx", + extensions: [ + "sea" + ] + }, + "application/x-sh": { + source: "apache", + compressible: true, + extensions: [ + "sh" + ] + }, + "application/x-shar": { + source: "apache", + extensions: [ + "shar" + ] + }, + "application/x-shockwave-flash": { + source: "apache", + compressible: false, + extensions: [ + "swf" + ] + }, + "application/x-silverlight-app": { + source: "apache", + extensions: [ + "xap" + ] + }, + "application/x-sql": { + source: "apache", + extensions: [ + "sql" + ] + }, + "application/x-stuffit": { + source: "apache", + compressible: false, + extensions: [ + "sit" + ] + }, + "application/x-stuffitx": { + source: "apache", + extensions: [ + "sitx" + ] + }, + "application/x-subrip": { + source: "apache", + extensions: [ + "srt" + ] + }, + "application/x-sv4cpio": { + source: "apache", + extensions: [ + "sv4cpio" + ] + }, + "application/x-sv4crc": { + source: "apache", + extensions: [ + "sv4crc" + ] + }, + "application/x-t3vm-image": { + source: "apache", + extensions: [ + "t3" + ] + }, + "application/x-tads": { + source: "apache", + extensions: [ + "gam" + ] + }, + "application/x-tar": { + source: "apache", + compressible: true, + extensions: [ + "tar" + ] + }, + "application/x-tcl": { + source: "apache", + extensions: [ + "tcl", + "tk" + ] + }, + "application/x-tex": { + source: "apache", + extensions: [ + "tex" + ] + }, + "application/x-tex-tfm": { + source: "apache", + extensions: [ + "tfm" + ] + }, + "application/x-texinfo": { + source: "apache", + extensions: [ + "texinfo", + "texi" + ] + }, + "application/x-tgif": { + source: "apache", + extensions: [ + "obj" + ] + }, + "application/x-ustar": { + source: "apache", + extensions: [ + "ustar" + ] + }, + "application/x-virtualbox-hdd": { + compressible: true, + extensions: [ + "hdd" + ] + }, + "application/x-virtualbox-ova": { + compressible: true, + extensions: [ + "ova" + ] + }, + "application/x-virtualbox-ovf": { + compressible: true, + extensions: [ + "ovf" + ] + }, + "application/x-virtualbox-vbox": { + compressible: true, + extensions: [ + "vbox" + ] + }, + "application/x-virtualbox-vbox-extpack": { + compressible: false, + extensions: [ + "vbox-extpack" + ] + }, + "application/x-virtualbox-vdi": { + compressible: true, + extensions: [ + "vdi" + ] + }, + "application/x-virtualbox-vhd": { + compressible: true, + extensions: [ + "vhd" + ] + }, + "application/x-virtualbox-vmdk": { + compressible: true, + extensions: [ + "vmdk" + ] + }, + "application/x-wais-source": { + source: "apache", + extensions: [ + "src" + ] + }, + "application/x-web-app-manifest+json": { + compressible: true, + extensions: [ + "webapp" + ] + }, + "application/x-www-form-urlencoded": { + source: "iana", + compressible: true + }, + "application/x-x509-ca-cert": { + source: "iana", + extensions: [ + "der", + "crt", + "pem" + ] + }, + "application/x-x509-ca-ra-cert": { + source: "iana" + }, + "application/x-x509-next-ca-cert": { + source: "iana" + }, + "application/x-xfig": { + source: "apache", + extensions: [ + "fig" + ] + }, + "application/x-xliff+xml": { + source: "apache", + compressible: true, + extensions: [ + "xlf" + ] + }, + "application/x-xpinstall": { + source: "apache", + compressible: false, + extensions: [ + "xpi" + ] + }, + "application/x-xz": { + source: "apache", + extensions: [ + "xz" + ] + }, + "application/x-zmachine": { + source: "apache", + extensions: [ + "z1", + "z2", + "z3", + "z4", + "z5", + "z6", + "z7", + "z8" + ] + }, + "application/x400-bp": { + source: "iana" + }, + "application/xacml+xml": { + source: "iana", + compressible: true + }, + "application/xaml+xml": { + source: "apache", + compressible: true, + extensions: [ + "xaml" + ] + }, + "application/xcap-att+xml": { + source: "iana", + compressible: true, + extensions: [ + "xav" + ] + }, + "application/xcap-caps+xml": { + source: "iana", + compressible: true, + extensions: [ + "xca" + ] + }, + "application/xcap-diff+xml": { + source: "iana", + compressible: true, + extensions: [ + "xdf" + ] + }, + "application/xcap-el+xml": { + source: "iana", + compressible: true, + extensions: [ + "xel" + ] + }, + "application/xcap-error+xml": { + source: "iana", + compressible: true + }, + "application/xcap-ns+xml": { + source: "iana", + compressible: true, + extensions: [ + "xns" + ] + }, + "application/xcon-conference-info+xml": { + source: "iana", + compressible: true + }, + "application/xcon-conference-info-diff+xml": { + source: "iana", + compressible: true + }, + "application/xenc+xml": { + source: "iana", + compressible: true, + extensions: [ + "xenc" + ] + }, + "application/xhtml+xml": { + source: "iana", + compressible: true, + extensions: [ + "xhtml", + "xht" + ] + }, + "application/xhtml-voice+xml": { + source: "apache", + compressible: true + }, + "application/xliff+xml": { + source: "iana", + compressible: true, + extensions: [ + "xlf" + ] + }, + "application/xml": { + source: "iana", + compressible: true, + extensions: [ + "xml", + "xsl", + "xsd", + "rng" + ] + }, + "application/xml-dtd": { + source: "iana", + compressible: true, + extensions: [ + "dtd" + ] + }, + "application/xml-external-parsed-entity": { + source: "iana" + }, + "application/xml-patch+xml": { + source: "iana", + compressible: true + }, + "application/xmpp+xml": { + source: "iana", + compressible: true + }, + "application/xop+xml": { + source: "iana", + compressible: true, + extensions: [ + "xop" + ] + }, + "application/xproc+xml": { + source: "apache", + compressible: true, + extensions: [ + "xpl" + ] + }, + "application/xslt+xml": { + source: "iana", + compressible: true, + extensions: [ + "xsl", + "xslt" + ] + }, + "application/xspf+xml": { + source: "apache", + compressible: true, + extensions: [ + "xspf" + ] + }, + "application/xv+xml": { + source: "iana", + compressible: true, + extensions: [ + "mxml", + "xhvml", + "xvml", + "xvm" + ] + }, + "application/yang": { + source: "iana", + extensions: [ + "yang" + ] + }, + "application/yang-data+json": { + source: "iana", + compressible: true + }, + "application/yang-data+xml": { + source: "iana", + compressible: true + }, + "application/yang-patch+json": { + source: "iana", + compressible: true + }, + "application/yang-patch+xml": { + source: "iana", + compressible: true + }, + "application/yin+xml": { + source: "iana", + compressible: true, + extensions: [ + "yin" + ] + }, + "application/zip": { + source: "iana", + compressible: false, + extensions: [ + "zip" + ] + }, + "application/zlib": { + source: "iana" + }, + "application/zstd": { + source: "iana" + }, + "audio/1d-interleaved-parityfec": { + source: "iana" + }, + "audio/32kadpcm": { + source: "iana" + }, + "audio/3gpp": { + source: "iana", + compressible: false, + extensions: [ + "3gpp" + ] + }, + "audio/3gpp2": { + source: "iana" + }, + "audio/aac": { + source: "iana" + }, + "audio/ac3": { + source: "iana" + }, + "audio/adpcm": { + source: "apache", + extensions: [ + "adp" + ] + }, + "audio/amr": { + source: "iana", + extensions: [ + "amr" + ] + }, + "audio/amr-wb": { + source: "iana" + }, + "audio/amr-wb+": { + source: "iana" + }, + "audio/aptx": { + source: "iana" + }, + "audio/asc": { + source: "iana" + }, + "audio/atrac-advanced-lossless": { + source: "iana" + }, + "audio/atrac-x": { + source: "iana" + }, + "audio/atrac3": { + source: "iana" + }, + "audio/basic": { + source: "iana", + compressible: false, + extensions: [ + "au", + "snd" + ] + }, + "audio/bv16": { + source: "iana" + }, + "audio/bv32": { + source: "iana" + }, + "audio/clearmode": { + source: "iana" + }, + "audio/cn": { + source: "iana" + }, + "audio/dat12": { + source: "iana" + }, + "audio/dls": { + source: "iana" + }, + "audio/dsr-es201108": { + source: "iana" + }, + "audio/dsr-es202050": { + source: "iana" + }, + "audio/dsr-es202211": { + source: "iana" + }, + "audio/dsr-es202212": { + source: "iana" + }, + "audio/dv": { + source: "iana" + }, + "audio/dvi4": { + source: "iana" + }, + "audio/eac3": { + source: "iana" + }, + "audio/encaprtp": { + source: "iana" + }, + "audio/evrc": { + source: "iana" + }, + "audio/evrc-qcp": { + source: "iana" + }, + "audio/evrc0": { + source: "iana" + }, + "audio/evrc1": { + source: "iana" + }, + "audio/evrcb": { + source: "iana" + }, + "audio/evrcb0": { + source: "iana" + }, + "audio/evrcb1": { + source: "iana" + }, + "audio/evrcnw": { + source: "iana" + }, + "audio/evrcnw0": { + source: "iana" + }, + "audio/evrcnw1": { + source: "iana" + }, + "audio/evrcwb": { + source: "iana" + }, + "audio/evrcwb0": { + source: "iana" + }, + "audio/evrcwb1": { + source: "iana" + }, + "audio/evs": { + source: "iana" + }, + "audio/flexfec": { + source: "iana" + }, + "audio/fwdred": { + source: "iana" + }, + "audio/g711-0": { + source: "iana" + }, + "audio/g719": { + source: "iana" + }, + "audio/g722": { + source: "iana" + }, + "audio/g7221": { + source: "iana" + }, + "audio/g723": { + source: "iana" + }, + "audio/g726-16": { + source: "iana" + }, + "audio/g726-24": { + source: "iana" + }, + "audio/g726-32": { + source: "iana" + }, + "audio/g726-40": { + source: "iana" + }, + "audio/g728": { + source: "iana" + }, + "audio/g729": { + source: "iana" + }, + "audio/g7291": { + source: "iana" + }, + "audio/g729d": { + source: "iana" + }, + "audio/g729e": { + source: "iana" + }, + "audio/gsm": { + source: "iana" + }, + "audio/gsm-efr": { + source: "iana" + }, + "audio/gsm-hr-08": { + source: "iana" + }, + "audio/ilbc": { + source: "iana" + }, + "audio/ip-mr_v2.5": { + source: "iana" + }, + "audio/isac": { + source: "apache" + }, + "audio/l16": { + source: "iana" + }, + "audio/l20": { + source: "iana" + }, + "audio/l24": { + source: "iana", + compressible: false + }, + "audio/l8": { + source: "iana" + }, + "audio/lpc": { + source: "iana" + }, + "audio/melp": { + source: "iana" + }, + "audio/melp1200": { + source: "iana" + }, + "audio/melp2400": { + source: "iana" + }, + "audio/melp600": { + source: "iana" + }, + "audio/mhas": { + source: "iana" + }, + "audio/midi": { + source: "apache", + extensions: [ + "mid", + "midi", + "kar", + "rmi" + ] + }, + "audio/mobile-xmf": { + source: "iana", + extensions: [ + "mxmf" + ] + }, + "audio/mp3": { + compressible: false, + extensions: [ + "mp3" + ] + }, + "audio/mp4": { + source: "iana", + compressible: false, + extensions: [ + "m4a", + "mp4a" + ] + }, + "audio/mp4a-latm": { + source: "iana" + }, + "audio/mpa": { + source: "iana" + }, + "audio/mpa-robust": { + source: "iana" + }, + "audio/mpeg": { + source: "iana", + compressible: false, + extensions: [ + "mpga", + "mp2", + "mp2a", + "mp3", + "m2a", + "m3a" + ] + }, + "audio/mpeg4-generic": { + source: "iana" + }, + "audio/musepack": { + source: "apache" + }, + "audio/ogg": { + source: "iana", + compressible: false, + extensions: [ + "oga", + "ogg", + "spx", + "opus" + ] + }, + "audio/opus": { + source: "iana" + }, + "audio/parityfec": { + source: "iana" + }, + "audio/pcma": { + source: "iana" + }, + "audio/pcma-wb": { + source: "iana" + }, + "audio/pcmu": { + source: "iana" + }, + "audio/pcmu-wb": { + source: "iana" + }, + "audio/prs.sid": { + source: "iana" + }, + "audio/qcelp": { + source: "iana" + }, + "audio/raptorfec": { + source: "iana" + }, + "audio/red": { + source: "iana" + }, + "audio/rtp-enc-aescm128": { + source: "iana" + }, + "audio/rtp-midi": { + source: "iana" + }, + "audio/rtploopback": { + source: "iana" + }, + "audio/rtx": { + source: "iana" + }, + "audio/s3m": { + source: "apache", + extensions: [ + "s3m" + ] + }, + "audio/scip": { + source: "iana" + }, + "audio/silk": { + source: "apache", + extensions: [ + "sil" + ] + }, + "audio/smv": { + source: "iana" + }, + "audio/smv-qcp": { + source: "iana" + }, + "audio/smv0": { + source: "iana" + }, + "audio/sofa": { + source: "iana" + }, + "audio/sp-midi": { + source: "iana" + }, + "audio/speex": { + source: "iana" + }, + "audio/t140c": { + source: "iana" + }, + "audio/t38": { + source: "iana" + }, + "audio/telephone-event": { + source: "iana" + }, + "audio/tetra_acelp": { + source: "iana" + }, + "audio/tetra_acelp_bb": { + source: "iana" + }, + "audio/tone": { + source: "iana" + }, + "audio/tsvcis": { + source: "iana" + }, + "audio/uemclip": { + source: "iana" + }, + "audio/ulpfec": { + source: "iana" + }, + "audio/usac": { + source: "iana" + }, + "audio/vdvi": { + source: "iana" + }, + "audio/vmr-wb": { + source: "iana" + }, + "audio/vnd.3gpp.iufp": { + source: "iana" + }, + "audio/vnd.4sb": { + source: "iana" + }, + "audio/vnd.audiokoz": { + source: "iana" + }, + "audio/vnd.celp": { + source: "iana" + }, + "audio/vnd.cisco.nse": { + source: "iana" + }, + "audio/vnd.cmles.radio-events": { + source: "iana" + }, + "audio/vnd.cns.anp1": { + source: "iana" + }, + "audio/vnd.cns.inf1": { + source: "iana" + }, + "audio/vnd.dece.audio": { + source: "iana", + extensions: [ + "uva", + "uvva" + ] + }, + "audio/vnd.digital-winds": { + source: "iana", + extensions: [ + "eol" + ] + }, + "audio/vnd.dlna.adts": { + source: "iana" + }, + "audio/vnd.dolby.heaac.1": { + source: "iana" + }, + "audio/vnd.dolby.heaac.2": { + source: "iana" + }, + "audio/vnd.dolby.mlp": { + source: "iana" + }, + "audio/vnd.dolby.mps": { + source: "iana" + }, + "audio/vnd.dolby.pl2": { + source: "iana" + }, + "audio/vnd.dolby.pl2x": { + source: "iana" + }, + "audio/vnd.dolby.pl2z": { + source: "iana" + }, + "audio/vnd.dolby.pulse.1": { + source: "iana" + }, + "audio/vnd.dra": { + source: "iana", + extensions: [ + "dra" + ] + }, + "audio/vnd.dts": { + source: "iana", + extensions: [ + "dts" + ] + }, + "audio/vnd.dts.hd": { + source: "iana", + extensions: [ + "dtshd" + ] + }, + "audio/vnd.dts.uhd": { + source: "iana" + }, + "audio/vnd.dvb.file": { + source: "iana" + }, + "audio/vnd.everad.plj": { + source: "iana" + }, + "audio/vnd.hns.audio": { + source: "iana" + }, + "audio/vnd.lucent.voice": { + source: "iana", + extensions: [ + "lvp" + ] + }, + "audio/vnd.ms-playready.media.pya": { + source: "iana", + extensions: [ + "pya" + ] + }, + "audio/vnd.nokia.mobile-xmf": { + source: "iana" + }, + "audio/vnd.nortel.vbk": { + source: "iana" + }, + "audio/vnd.nuera.ecelp4800": { + source: "iana", + extensions: [ + "ecelp4800" + ] + }, + "audio/vnd.nuera.ecelp7470": { + source: "iana", + extensions: [ + "ecelp7470" + ] + }, + "audio/vnd.nuera.ecelp9600": { + source: "iana", + extensions: [ + "ecelp9600" + ] + }, + "audio/vnd.octel.sbc": { + source: "iana" + }, + "audio/vnd.presonus.multitrack": { + source: "iana" + }, + "audio/vnd.qcelp": { + source: "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + source: "iana" + }, + "audio/vnd.rip": { + source: "iana", + extensions: [ + "rip" + ] + }, + "audio/vnd.rn-realaudio": { + compressible: false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + source: "iana" + }, + "audio/vnd.vmx.cvsd": { + source: "iana" + }, + "audio/vnd.wave": { + compressible: false + }, + "audio/vorbis": { + source: "iana", + compressible: false + }, + "audio/vorbis-config": { + source: "iana" + }, + "audio/wav": { + compressible: false, + extensions: [ + "wav" + ] + }, + "audio/wave": { + compressible: false, + extensions: [ + "wav" + ] + }, + "audio/webm": { + source: "apache", + compressible: false, + extensions: [ + "weba" + ] + }, + "audio/x-aac": { + source: "apache", + compressible: false, + extensions: [ + "aac" + ] + }, + "audio/x-aiff": { + source: "apache", + extensions: [ + "aif", + "aiff", + "aifc" + ] + }, + "audio/x-caf": { + source: "apache", + compressible: false, + extensions: [ + "caf" + ] + }, + "audio/x-flac": { + source: "apache", + extensions: [ + "flac" + ] + }, + "audio/x-m4a": { + source: "nginx", + extensions: [ + "m4a" + ] + }, + "audio/x-matroska": { + source: "apache", + extensions: [ + "mka" + ] + }, + "audio/x-mpegurl": { + source: "apache", + extensions: [ + "m3u" + ] + }, + "audio/x-ms-wax": { + source: "apache", + extensions: [ + "wax" + ] + }, + "audio/x-ms-wma": { + source: "apache", + extensions: [ + "wma" + ] + }, + "audio/x-pn-realaudio": { + source: "apache", + extensions: [ + "ram", + "ra" + ] + }, + "audio/x-pn-realaudio-plugin": { + source: "apache", + extensions: [ + "rmp" + ] + }, + "audio/x-realaudio": { + source: "nginx", + extensions: [ + "ra" + ] + }, + "audio/x-tta": { + source: "apache" + }, + "audio/x-wav": { + source: "apache", + extensions: [ + "wav" + ] + }, + "audio/xm": { + source: "apache", + extensions: [ + "xm" + ] + }, + "chemical/x-cdx": { + source: "apache", + extensions: [ + "cdx" + ] + }, + "chemical/x-cif": { + source: "apache", + extensions: [ + "cif" + ] + }, + "chemical/x-cmdf": { + source: "apache", + extensions: [ + "cmdf" + ] + }, + "chemical/x-cml": { + source: "apache", + extensions: [ + "cml" + ] + }, + "chemical/x-csml": { + source: "apache", + extensions: [ + "csml" + ] + }, + "chemical/x-pdb": { + source: "apache" + }, + "chemical/x-xyz": { + source: "apache", + extensions: [ + "xyz" + ] + }, + "font/collection": { + source: "iana", + extensions: [ + "ttc" + ] + }, + "font/otf": { + source: "iana", + compressible: true, + extensions: [ + "otf" + ] + }, + "font/sfnt": { + source: "iana" + }, + "font/ttf": { + source: "iana", + compressible: true, + extensions: [ + "ttf" + ] + }, + "font/woff": { + source: "iana", + extensions: [ + "woff" + ] + }, + "font/woff2": { + source: "iana", + extensions: [ + "woff2" + ] + }, + "image/aces": { + source: "iana", + extensions: [ + "exr" + ] + }, + "image/apng": { + compressible: false, + extensions: [ + "apng" + ] + }, + "image/avci": { + source: "iana", + extensions: [ + "avci" + ] + }, + "image/avcs": { + source: "iana", + extensions: [ + "avcs" + ] + }, + "image/avif": { + source: "iana", + compressible: false, + extensions: [ + "avif" + ] + }, + "image/bmp": { + source: "iana", + compressible: true, + extensions: [ + "bmp" + ] + }, + "image/cgm": { + source: "iana", + extensions: [ + "cgm" + ] + }, + "image/dicom-rle": { + source: "iana", + extensions: [ + "drle" + ] + }, + "image/emf": { + source: "iana", + extensions: [ + "emf" + ] + }, + "image/fits": { + source: "iana", + extensions: [ + "fits" + ] + }, + "image/g3fax": { + source: "iana", + extensions: [ + "g3" + ] + }, + "image/gif": { + source: "iana", + compressible: false, + extensions: [ + "gif" + ] + }, + "image/heic": { + source: "iana", + extensions: [ + "heic" + ] + }, + "image/heic-sequence": { + source: "iana", + extensions: [ + "heics" + ] + }, + "image/heif": { + source: "iana", + extensions: [ + "heif" + ] + }, + "image/heif-sequence": { + source: "iana", + extensions: [ + "heifs" + ] + }, + "image/hej2k": { + source: "iana", + extensions: [ + "hej2" + ] + }, + "image/hsj2": { + source: "iana", + extensions: [ + "hsj2" + ] + }, + "image/ief": { + source: "iana", + extensions: [ + "ief" + ] + }, + "image/jls": { + source: "iana", + extensions: [ + "jls" + ] + }, + "image/jp2": { + source: "iana", + compressible: false, + extensions: [ + "jp2", + "jpg2" + ] + }, + "image/jpeg": { + source: "iana", + compressible: false, + extensions: [ + "jpeg", + "jpg", + "jpe" + ] + }, + "image/jph": { + source: "iana", + extensions: [ + "jph" + ] + }, + "image/jphc": { + source: "iana", + extensions: [ + "jhc" + ] + }, + "image/jpm": { + source: "iana", + compressible: false, + extensions: [ + "jpm" + ] + }, + "image/jpx": { + source: "iana", + compressible: false, + extensions: [ + "jpx", + "jpf" + ] + }, + "image/jxr": { + source: "iana", + extensions: [ + "jxr" + ] + }, + "image/jxra": { + source: "iana", + extensions: [ + "jxra" + ] + }, + "image/jxrs": { + source: "iana", + extensions: [ + "jxrs" + ] + }, + "image/jxs": { + source: "iana", + extensions: [ + "jxs" + ] + }, + "image/jxsc": { + source: "iana", + extensions: [ + "jxsc" + ] + }, + "image/jxsi": { + source: "iana", + extensions: [ + "jxsi" + ] + }, + "image/jxss": { + source: "iana", + extensions: [ + "jxss" + ] + }, + "image/ktx": { + source: "iana", + extensions: [ + "ktx" + ] + }, + "image/ktx2": { + source: "iana", + extensions: [ + "ktx2" + ] + }, + "image/naplps": { + source: "iana" + }, + "image/pjpeg": { + compressible: false + }, + "image/png": { + source: "iana", + compressible: false, + extensions: [ + "png" + ] + }, + "image/prs.btif": { + source: "iana", + extensions: [ + "btif" + ] + }, + "image/prs.pti": { + source: "iana", + extensions: [ + "pti" + ] + }, + "image/pwg-raster": { + source: "iana" + }, + "image/sgi": { + source: "apache", + extensions: [ + "sgi" + ] + }, + "image/svg+xml": { + source: "iana", + compressible: true, + extensions: [ + "svg", + "svgz" + ] + }, + "image/t38": { + source: "iana", + extensions: [ + "t38" + ] + }, + "image/tiff": { + source: "iana", + compressible: false, + extensions: [ + "tif", + "tiff" + ] + }, + "image/tiff-fx": { + source: "iana", + extensions: [ + "tfx" + ] + }, + "image/vnd.adobe.photoshop": { + source: "iana", + compressible: true, + extensions: [ + "psd" + ] + }, + "image/vnd.airzip.accelerator.azv": { + source: "iana", + extensions: [ + "azv" + ] + }, + "image/vnd.cns.inf2": { + source: "iana" + }, + "image/vnd.dece.graphic": { + source: "iana", + extensions: [ + "uvi", + "uvvi", + "uvg", + "uvvg" + ] + }, + "image/vnd.djvu": { + source: "iana", + extensions: [ + "djvu", + "djv" + ] + }, + "image/vnd.dvb.subtitle": { + source: "iana", + extensions: [ + "sub" + ] + }, + "image/vnd.dwg": { + source: "iana", + extensions: [ + "dwg" + ] + }, + "image/vnd.dxf": { + source: "iana", + extensions: [ + "dxf" + ] + }, + "image/vnd.fastbidsheet": { + source: "iana", + extensions: [ + "fbs" + ] + }, + "image/vnd.fpx": { + source: "iana", + extensions: [ + "fpx" + ] + }, + "image/vnd.fst": { + source: "iana", + extensions: [ + "fst" + ] + }, + "image/vnd.fujixerox.edmics-mmr": { + source: "iana", + extensions: [ + "mmr" + ] + }, + "image/vnd.fujixerox.edmics-rlc": { + source: "iana", + extensions: [ + "rlc" + ] + }, + "image/vnd.globalgraphics.pgb": { + source: "iana" + }, + "image/vnd.microsoft.icon": { + source: "iana", + compressible: true, + extensions: [ + "ico" + ] + }, + "image/vnd.mix": { + source: "iana" + }, + "image/vnd.mozilla.apng": { + source: "iana" + }, + "image/vnd.ms-dds": { + compressible: true, + extensions: [ + "dds" + ] + }, + "image/vnd.ms-modi": { + source: "iana", + extensions: [ + "mdi" + ] + }, + "image/vnd.ms-photo": { + source: "apache", + extensions: [ + "wdp" + ] + }, + "image/vnd.net-fpx": { + source: "iana", + extensions: [ + "npx" + ] + }, + "image/vnd.pco.b16": { + source: "iana", + extensions: [ + "b16" + ] + }, + "image/vnd.radiance": { + source: "iana" + }, + "image/vnd.sealed.png": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + source: "iana" + }, + "image/vnd.svf": { + source: "iana" + }, + "image/vnd.tencent.tap": { + source: "iana", + extensions: [ + "tap" + ] + }, + "image/vnd.valve.source.texture": { + source: "iana", + extensions: [ + "vtf" + ] + }, + "image/vnd.wap.wbmp": { + source: "iana", + extensions: [ + "wbmp" + ] + }, + "image/vnd.xiff": { + source: "iana", + extensions: [ + "xif" + ] + }, + "image/vnd.zbrush.pcx": { + source: "iana", + extensions: [ + "pcx" + ] + }, + "image/webp": { + source: "apache", + extensions: [ + "webp" + ] + }, + "image/wmf": { + source: "iana", + extensions: [ + "wmf" + ] + }, + "image/x-3ds": { + source: "apache", + extensions: [ + "3ds" + ] + }, + "image/x-cmu-raster": { + source: "apache", + extensions: [ + "ras" + ] + }, + "image/x-cmx": { + source: "apache", + extensions: [ + "cmx" + ] + }, + "image/x-freehand": { + source: "apache", + extensions: [ + "fh", + "fhc", + "fh4", + "fh5", + "fh7" + ] + }, + "image/x-icon": { + source: "apache", + compressible: true, + extensions: [ + "ico" + ] + }, + "image/x-jng": { + source: "nginx", + extensions: [ + "jng" + ] + }, + "image/x-mrsid-image": { + source: "apache", + extensions: [ + "sid" + ] + }, + "image/x-ms-bmp": { + source: "nginx", + compressible: true, + extensions: [ + "bmp" + ] + }, + "image/x-pcx": { + source: "apache", + extensions: [ + "pcx" + ] + }, + "image/x-pict": { + source: "apache", + extensions: [ + "pic", + "pct" + ] + }, + "image/x-portable-anymap": { + source: "apache", + extensions: [ + "pnm" + ] + }, + "image/x-portable-bitmap": { + source: "apache", + extensions: [ + "pbm" + ] + }, + "image/x-portable-graymap": { + source: "apache", + extensions: [ + "pgm" + ] + }, + "image/x-portable-pixmap": { + source: "apache", + extensions: [ + "ppm" + ] + }, + "image/x-rgb": { + source: "apache", + extensions: [ + "rgb" + ] + }, + "image/x-tga": { + source: "apache", + extensions: [ + "tga" + ] + }, + "image/x-xbitmap": { + source: "apache", + extensions: [ + "xbm" + ] + }, + "image/x-xcf": { + compressible: false + }, + "image/x-xpixmap": { + source: "apache", + extensions: [ + "xpm" + ] + }, + "image/x-xwindowdump": { + source: "apache", + extensions: [ + "xwd" + ] + }, + "message/cpim": { + source: "iana" + }, + "message/delivery-status": { + source: "iana" + }, + "message/disposition-notification": { + source: "iana", + extensions: [ + "disposition-notification" + ] + }, + "message/external-body": { + source: "iana" + }, + "message/feedback-report": { + source: "iana" + }, + "message/global": { + source: "iana", + extensions: [ + "u8msg" + ] + }, + "message/global-delivery-status": { + source: "iana", + extensions: [ + "u8dsn" + ] + }, + "message/global-disposition-notification": { + source: "iana", + extensions: [ + "u8mdn" + ] + }, + "message/global-headers": { + source: "iana", + extensions: [ + "u8hdr" + ] + }, + "message/http": { + source: "iana", + compressible: false + }, + "message/imdn+xml": { + source: "iana", + compressible: true + }, + "message/news": { + source: "iana" + }, + "message/partial": { + source: "iana", + compressible: false + }, + "message/rfc822": { + source: "iana", + compressible: true, + extensions: [ + "eml", + "mime" + ] + }, + "message/s-http": { + source: "iana" + }, + "message/sip": { + source: "iana" + }, + "message/sipfrag": { + source: "iana" + }, + "message/tracking-status": { + source: "iana" + }, + "message/vnd.si.simp": { + source: "iana" + }, + "message/vnd.wfa.wsc": { + source: "iana", + extensions: [ + "wsc" + ] + }, + "model/3mf": { + source: "iana", + extensions: [ + "3mf" + ] + }, + "model/e57": { + source: "iana" + }, + "model/gltf+json": { + source: "iana", + compressible: true, + extensions: [ + "gltf" + ] + }, + "model/gltf-binary": { + source: "iana", + compressible: true, + extensions: [ + "glb" + ] + }, + "model/iges": { + source: "iana", + compressible: false, + extensions: [ + "igs", + "iges" + ] + }, + "model/mesh": { + source: "iana", + compressible: false, + extensions: [ + "msh", + "mesh", + "silo" + ] + }, + "model/mtl": { + source: "iana", + extensions: [ + "mtl" + ] + }, + "model/obj": { + source: "iana", + extensions: [ + "obj" + ] + }, + "model/step": { + source: "iana" + }, + "model/step+xml": { + source: "iana", + compressible: true, + extensions: [ + "stpx" + ] + }, + "model/step+zip": { + source: "iana", + compressible: false, + extensions: [ + "stpz" + ] + }, + "model/step-xml+zip": { + source: "iana", + compressible: false, + extensions: [ + "stpxz" + ] + }, + "model/stl": { + source: "iana", + extensions: [ + "stl" + ] + }, + "model/vnd.collada+xml": { + source: "iana", + compressible: true, + extensions: [ + "dae" + ] + }, + "model/vnd.dwf": { + source: "iana", + extensions: [ + "dwf" + ] + }, + "model/vnd.flatland.3dml": { + source: "iana" + }, + "model/vnd.gdl": { + source: "iana", + extensions: [ + "gdl" + ] + }, + "model/vnd.gs-gdl": { + source: "apache" + }, + "model/vnd.gs.gdl": { + source: "iana" + }, + "model/vnd.gtw": { + source: "iana", + extensions: [ + "gtw" + ] + }, + "model/vnd.moml+xml": { + source: "iana", + compressible: true + }, + "model/vnd.mts": { + source: "iana", + extensions: [ + "mts" + ] + }, + "model/vnd.opengex": { + source: "iana", + extensions: [ + "ogex" + ] + }, + "model/vnd.parasolid.transmit.binary": { + source: "iana", + extensions: [ + "x_b" + ] + }, + "model/vnd.parasolid.transmit.text": { + source: "iana", + extensions: [ + "x_t" + ] + }, + "model/vnd.pytha.pyox": { + source: "iana" + }, + "model/vnd.rosette.annotated-data-model": { + source: "iana" + }, + "model/vnd.sap.vds": { + source: "iana", + extensions: [ + "vds" + ] + }, + "model/vnd.usdz+zip": { + source: "iana", + compressible: false, + extensions: [ + "usdz" + ] + }, + "model/vnd.valve.source.compiled-map": { + source: "iana", + extensions: [ + "bsp" + ] + }, + "model/vnd.vtu": { + source: "iana", + extensions: [ + "vtu" + ] + }, + "model/vrml": { + source: "iana", + compressible: false, + extensions: [ + "wrl", + "vrml" + ] + }, + "model/x3d+binary": { + source: "apache", + compressible: false, + extensions: [ + "x3db", + "x3dbz" + ] + }, + "model/x3d+fastinfoset": { + source: "iana", + extensions: [ + "x3db" + ] + }, + "model/x3d+vrml": { + source: "apache", + compressible: false, + extensions: [ + "x3dv", + "x3dvz" + ] + }, + "model/x3d+xml": { + source: "iana", + compressible: true, + extensions: [ + "x3d", + "x3dz" + ] + }, + "model/x3d-vrml": { + source: "iana", + extensions: [ + "x3dv" + ] + }, + "multipart/alternative": { + source: "iana", + compressible: false + }, + "multipart/appledouble": { + source: "iana" + }, + "multipart/byteranges": { + source: "iana" + }, + "multipart/digest": { + source: "iana" + }, + "multipart/encrypted": { + source: "iana", + compressible: false + }, + "multipart/form-data": { + source: "iana", + compressible: false + }, + "multipart/header-set": { + source: "iana" + }, + "multipart/mixed": { + source: "iana" + }, + "multipart/multilingual": { + source: "iana" + }, + "multipart/parallel": { + source: "iana" + }, + "multipart/related": { + source: "iana", + compressible: false + }, + "multipart/report": { + source: "iana" + }, + "multipart/signed": { + source: "iana", + compressible: false + }, + "multipart/vnd.bint.med-plus": { + source: "iana" + }, + "multipart/voice-message": { + source: "iana" + }, + "multipart/x-mixed-replace": { + source: "iana" + }, + "text/1d-interleaved-parityfec": { + source: "iana" + }, + "text/cache-manifest": { + source: "iana", + compressible: true, + extensions: [ + "appcache", + "manifest" + ] + }, + "text/calendar": { + source: "iana", + extensions: [ + "ics", + "ifb" + ] + }, + "text/calender": { + compressible: true + }, + "text/cmd": { + compressible: true + }, + "text/coffeescript": { + extensions: [ + "coffee", + "litcoffee" + ] + }, + "text/cql": { + source: "iana" + }, + "text/cql-expression": { + source: "iana" + }, + "text/cql-identifier": { + source: "iana" + }, + "text/css": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "css" + ] + }, + "text/csv": { + source: "iana", + compressible: true, + extensions: [ + "csv" + ] + }, + "text/csv-schema": { + source: "iana" + }, + "text/directory": { + source: "iana" + }, + "text/dns": { + source: "iana" + }, + "text/ecmascript": { + source: "iana" + }, + "text/encaprtp": { + source: "iana" + }, + "text/enriched": { + source: "iana" + }, + "text/fhirpath": { + source: "iana" + }, + "text/flexfec": { + source: "iana" + }, + "text/fwdred": { + source: "iana" + }, + "text/gff3": { + source: "iana" + }, + "text/grammar-ref-list": { + source: "iana" + }, + "text/html": { + source: "iana", + compressible: true, + extensions: [ + "html", + "htm", + "shtml" + ] + }, + "text/jade": { + extensions: [ + "jade" + ] + }, + "text/javascript": { + source: "iana", + compressible: true + }, + "text/jcr-cnd": { + source: "iana" + }, + "text/jsx": { + compressible: true, + extensions: [ + "jsx" + ] + }, + "text/less": { + compressible: true, + extensions: [ + "less" + ] + }, + "text/markdown": { + source: "iana", + compressible: true, + extensions: [ + "markdown", + "md" + ] + }, + "text/mathml": { + source: "nginx", + extensions: [ + "mml" + ] + }, + "text/mdx": { + compressible: true, + extensions: [ + "mdx" + ] + }, + "text/mizar": { + source: "iana" + }, + "text/n3": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "n3" + ] + }, + "text/parameters": { + source: "iana", + charset: "UTF-8" + }, + "text/parityfec": { + source: "iana" + }, + "text/plain": { + source: "iana", + compressible: true, + extensions: [ + "txt", + "text", + "conf", + "def", + "list", + "log", + "in", + "ini" + ] + }, + "text/provenance-notation": { + source: "iana", + charset: "UTF-8" + }, + "text/prs.fallenstein.rst": { + source: "iana" + }, + "text/prs.lines.tag": { + source: "iana", + extensions: [ + "dsc" + ] + }, + "text/prs.prop.logic": { + source: "iana" + }, + "text/raptorfec": { + source: "iana" + }, + "text/red": { + source: "iana" + }, + "text/rfc822-headers": { + source: "iana" + }, + "text/richtext": { + source: "iana", + compressible: true, + extensions: [ + "rtx" + ] + }, + "text/rtf": { + source: "iana", + compressible: true, + extensions: [ + "rtf" + ] + }, + "text/rtp-enc-aescm128": { + source: "iana" + }, + "text/rtploopback": { + source: "iana" + }, + "text/rtx": { + source: "iana" + }, + "text/sgml": { + source: "iana", + extensions: [ + "sgml", + "sgm" + ] + }, + "text/shaclc": { + source: "iana" + }, + "text/shex": { + source: "iana", + extensions: [ + "shex" + ] + }, + "text/slim": { + extensions: [ + "slim", + "slm" + ] + }, + "text/spdx": { + source: "iana", + extensions: [ + "spdx" + ] + }, + "text/strings": { + source: "iana" + }, + "text/stylus": { + extensions: [ + "stylus", + "styl" + ] + }, + "text/t140": { + source: "iana" + }, + "text/tab-separated-values": { + source: "iana", + compressible: true, + extensions: [ + "tsv" + ] + }, + "text/troff": { + source: "iana", + extensions: [ + "t", + "tr", + "roff", + "man", + "me", + "ms" + ] + }, + "text/turtle": { + source: "iana", + charset: "UTF-8", + extensions: [ + "ttl" + ] + }, + "text/ulpfec": { + source: "iana" + }, + "text/uri-list": { + source: "iana", + compressible: true, + extensions: [ + "uri", + "uris", + "urls" + ] + }, + "text/vcard": { + source: "iana", + compressible: true, + extensions: [ + "vcard" + ] + }, + "text/vnd.a": { + source: "iana" + }, + "text/vnd.abc": { + source: "iana" + }, + "text/vnd.ascii-art": { + source: "iana" + }, + "text/vnd.curl": { + source: "iana", + extensions: [ + "curl" + ] + }, + "text/vnd.curl.dcurl": { + source: "apache", + extensions: [ + "dcurl" + ] + }, + "text/vnd.curl.mcurl": { + source: "apache", + extensions: [ + "mcurl" + ] + }, + "text/vnd.curl.scurl": { + source: "apache", + extensions: [ + "scurl" + ] + }, + "text/vnd.debian.copyright": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.dmclientscript": { + source: "iana" + }, + "text/vnd.dvb.subtitle": { + source: "iana", + extensions: [ + "sub" + ] + }, + "text/vnd.esmertec.theme-descriptor": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + source: "iana", + extensions: [ + "ged" + ] + }, + "text/vnd.ficlab.flt": { + source: "iana" + }, + "text/vnd.fly": { + source: "iana", + extensions: [ + "fly" + ] + }, + "text/vnd.fmi.flexstor": { + source: "iana", + extensions: [ + "flx" + ] + }, + "text/vnd.gml": { + source: "iana" + }, + "text/vnd.graphviz": { + source: "iana", + extensions: [ + "gv" + ] + }, + "text/vnd.hans": { + source: "iana" + }, + "text/vnd.hgl": { + source: "iana" + }, + "text/vnd.in3d.3dml": { + source: "iana", + extensions: [ + "3dml" + ] + }, + "text/vnd.in3d.spot": { + source: "iana", + extensions: [ + "spot" + ] + }, + "text/vnd.iptc.newsml": { + source: "iana" + }, + "text/vnd.iptc.nitf": { + source: "iana" + }, + "text/vnd.latex-z": { + source: "iana" + }, + "text/vnd.motorola.reflex": { + source: "iana" + }, + "text/vnd.ms-mediapackage": { + source: "iana" + }, + "text/vnd.net2phone.commcenter.command": { + source: "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + source: "iana" + }, + "text/vnd.senx.warpscript": { + source: "iana" + }, + "text/vnd.si.uricatalogue": { + source: "iana" + }, + "text/vnd.sosi": { + source: "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + source: "iana", + charset: "UTF-8", + extensions: [ + "jad" + ] + }, + "text/vnd.trolltech.linguist": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.wap.si": { + source: "iana" + }, + "text/vnd.wap.sl": { + source: "iana" + }, + "text/vnd.wap.wml": { + source: "iana", + extensions: [ + "wml" + ] + }, + "text/vnd.wap.wmlscript": { + source: "iana", + extensions: [ + "wmls" + ] + }, + "text/vtt": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "vtt" + ] + }, + "text/x-asm": { + source: "apache", + extensions: [ + "s", + "asm" + ] + }, + "text/x-c": { + source: "apache", + extensions: [ + "c", + "cc", + "cxx", + "cpp", + "h", + "hh", + "dic" + ] + }, + "text/x-component": { + source: "nginx", + extensions: [ + "htc" + ] + }, + "text/x-fortran": { + source: "apache", + extensions: [ + "f", + "for", + "f77", + "f90" + ] + }, + "text/x-gwt-rpc": { + compressible: true + }, + "text/x-handlebars-template": { + extensions: [ + "hbs" + ] + }, + "text/x-java-source": { + source: "apache", + extensions: [ + "java" + ] + }, + "text/x-jquery-tmpl": { + compressible: true + }, + "text/x-lua": { + extensions: [ + "lua" + ] + }, + "text/x-markdown": { + compressible: true, + extensions: [ + "mkd" + ] + }, + "text/x-nfo": { + source: "apache", + extensions: [ + "nfo" + ] + }, + "text/x-opml": { + source: "apache", + extensions: [ + "opml" + ] + }, + "text/x-org": { + compressible: true, + extensions: [ + "org" + ] + }, + "text/x-pascal": { + source: "apache", + extensions: [ + "p", + "pas" + ] + }, + "text/x-processing": { + compressible: true, + extensions: [ + "pde" + ] + }, + "text/x-sass": { + extensions: [ + "sass" + ] + }, + "text/x-scss": { + extensions: [ + "scss" + ] + }, + "text/x-setext": { + source: "apache", + extensions: [ + "etx" + ] + }, + "text/x-sfv": { + source: "apache", + extensions: [ + "sfv" + ] + }, + "text/x-suse-ymp": { + compressible: true, + extensions: [ + "ymp" + ] + }, + "text/x-uuencode": { + source: "apache", + extensions: [ + "uu" + ] + }, + "text/x-vcalendar": { + source: "apache", + extensions: [ + "vcs" + ] + }, + "text/x-vcard": { + source: "apache", + extensions: [ + "vcf" + ] + }, + "text/xml": { + source: "iana", + compressible: true, + extensions: [ + "xml" + ] + }, + "text/xml-external-parsed-entity": { + source: "iana" + }, + "text/yaml": { + compressible: true, + extensions: [ + "yaml", + "yml" + ] + }, + "video/1d-interleaved-parityfec": { + source: "iana" + }, + "video/3gpp": { + source: "iana", + extensions: [ + "3gp", + "3gpp" + ] + }, + "video/3gpp-tt": { + source: "iana" + }, + "video/3gpp2": { + source: "iana", + extensions: [ + "3g2" + ] + }, + "video/av1": { + source: "iana" + }, + "video/bmpeg": { + source: "iana" + }, + "video/bt656": { + source: "iana" + }, + "video/celb": { + source: "iana" + }, + "video/dv": { + source: "iana" + }, + "video/encaprtp": { + source: "iana" + }, + "video/ffv1": { + source: "iana" + }, + "video/flexfec": { + source: "iana" + }, + "video/h261": { + source: "iana", + extensions: [ + "h261" + ] + }, + "video/h263": { + source: "iana", + extensions: [ + "h263" + ] + }, + "video/h263-1998": { + source: "iana" + }, + "video/h263-2000": { + source: "iana" + }, + "video/h264": { + source: "iana", + extensions: [ + "h264" + ] + }, + "video/h264-rcdo": { + source: "iana" + }, + "video/h264-svc": { + source: "iana" + }, + "video/h265": { + source: "iana" + }, + "video/iso.segment": { + source: "iana", + extensions: [ + "m4s" + ] + }, + "video/jpeg": { + source: "iana", + extensions: [ + "jpgv" + ] + }, + "video/jpeg2000": { + source: "iana" + }, + "video/jpm": { + source: "apache", + extensions: [ + "jpm", + "jpgm" + ] + }, + "video/jxsv": { + source: "iana" + }, + "video/mj2": { + source: "iana", + extensions: [ + "mj2", + "mjp2" + ] + }, + "video/mp1s": { + source: "iana" + }, + "video/mp2p": { + source: "iana" + }, + "video/mp2t": { + source: "iana", + extensions: [ + "ts" + ] + }, + "video/mp4": { + source: "iana", + compressible: false, + extensions: [ + "mp4", + "mp4v", + "mpg4" + ] + }, + "video/mp4v-es": { + source: "iana" + }, + "video/mpeg": { + source: "iana", + compressible: false, + extensions: [ + "mpeg", + "mpg", + "mpe", + "m1v", + "m2v" + ] + }, + "video/mpeg4-generic": { + source: "iana" + }, + "video/mpv": { + source: "iana" + }, + "video/nv": { + source: "iana" + }, + "video/ogg": { + source: "iana", + compressible: false, + extensions: [ + "ogv" + ] + }, + "video/parityfec": { + source: "iana" + }, + "video/pointer": { + source: "iana" + }, + "video/quicktime": { + source: "iana", + compressible: false, + extensions: [ + "qt", + "mov" + ] + }, + "video/raptorfec": { + source: "iana" + }, + "video/raw": { + source: "iana" + }, + "video/rtp-enc-aescm128": { + source: "iana" + }, + "video/rtploopback": { + source: "iana" + }, + "video/rtx": { + source: "iana" + }, + "video/scip": { + source: "iana" + }, + "video/smpte291": { + source: "iana" + }, + "video/smpte292m": { + source: "iana" + }, + "video/ulpfec": { + source: "iana" + }, + "video/vc1": { + source: "iana" + }, + "video/vc2": { + source: "iana" + }, + "video/vnd.cctv": { + source: "iana" + }, + "video/vnd.dece.hd": { + source: "iana", + extensions: [ + "uvh", + "uvvh" + ] + }, + "video/vnd.dece.mobile": { + source: "iana", + extensions: [ + "uvm", + "uvvm" + ] + }, + "video/vnd.dece.mp4": { + source: "iana" + }, + "video/vnd.dece.pd": { + source: "iana", + extensions: [ + "uvp", + "uvvp" + ] + }, + "video/vnd.dece.sd": { + source: "iana", + extensions: [ + "uvs", + "uvvs" + ] + }, + "video/vnd.dece.video": { + source: "iana", + extensions: [ + "uvv", + "uvvv" + ] + }, + "video/vnd.directv.mpeg": { + source: "iana" + }, + "video/vnd.directv.mpeg-tts": { + source: "iana" + }, + "video/vnd.dlna.mpeg-tts": { + source: "iana" + }, + "video/vnd.dvb.file": { + source: "iana", + extensions: [ + "dvb" + ] + }, + "video/vnd.fvt": { + source: "iana", + extensions: [ + "fvt" + ] + }, + "video/vnd.hns.video": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.ttsavc": { + source: "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + source: "iana" + }, + "video/vnd.motorola.video": { + source: "iana" + }, + "video/vnd.motorola.videop": { + source: "iana" + }, + "video/vnd.mpegurl": { + source: "iana", + extensions: [ + "mxu", + "m4u" + ] + }, + "video/vnd.ms-playready.media.pyv": { + source: "iana", + extensions: [ + "pyv" + ] + }, + "video/vnd.nokia.interleaved-multimedia": { + source: "iana" + }, + "video/vnd.nokia.mp4vr": { + source: "iana" + }, + "video/vnd.nokia.videovoip": { + source: "iana" + }, + "video/vnd.objectvideo": { + source: "iana" + }, + "video/vnd.radgamettools.bink": { + source: "iana" + }, + "video/vnd.radgamettools.smacker": { + source: "iana" + }, + "video/vnd.sealed.mpeg1": { + source: "iana" + }, + "video/vnd.sealed.mpeg4": { + source: "iana" + }, + "video/vnd.sealed.swf": { + source: "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + source: "iana" + }, + "video/vnd.uvvu.mp4": { + source: "iana", + extensions: [ + "uvu", + "uvvu" + ] + }, + "video/vnd.vivo": { + source: "iana", + extensions: [ + "viv" + ] + }, + "video/vnd.youtube.yt": { + source: "iana" + }, + "video/vp8": { + source: "iana" + }, + "video/vp9": { + source: "iana" + }, + "video/webm": { + source: "apache", + compressible: false, + extensions: [ + "webm" + ] + }, + "video/x-f4v": { + source: "apache", + extensions: [ + "f4v" + ] + }, + "video/x-fli": { + source: "apache", + extensions: [ + "fli" + ] + }, + "video/x-flv": { + source: "apache", + compressible: false, + extensions: [ + "flv" + ] + }, + "video/x-m4v": { + source: "apache", + extensions: [ + "m4v" + ] + }, + "video/x-matroska": { + source: "apache", + compressible: false, + extensions: [ + "mkv", + "mk3d", + "mks" + ] + }, + "video/x-mng": { + source: "apache", + extensions: [ + "mng" + ] + }, + "video/x-ms-asf": { + source: "apache", + extensions: [ + "asf", + "asx" + ] + }, + "video/x-ms-vob": { + source: "apache", + extensions: [ + "vob" + ] + }, + "video/x-ms-wm": { + source: "apache", + extensions: [ + "wm" + ] + }, + "video/x-ms-wmv": { + source: "apache", + compressible: false, + extensions: [ + "wmv" + ] + }, + "video/x-ms-wmx": { + source: "apache", + extensions: [ + "wmx" + ] + }, + "video/x-ms-wvx": { + source: "apache", + extensions: [ + "wvx" + ] + }, + "video/x-msvideo": { + source: "apache", + extensions: [ + "avi" + ] + }, + "video/x-sgi-movie": { + source: "apache", + extensions: [ + "movie" + ] + }, + "video/x-smv": { + source: "apache", + extensions: [ + "smv" + ] + }, + "x-conference/x-cooltalk": { + source: "apache", + extensions: [ + "ice" + ] + }, + "x-shader/x-fragment": { + compressible: true + }, + "x-shader/x-vertex": { + compressible: true + } + }; + + /*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + + /** + * Module exports. + */ + + var mimeDb = require$$0; + + /*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + (function (exports) { + + /** + * Module dependencies. + * @private + */ + + var db = mimeDb; + var extname = require$$2.extname; + + /** + * Module variables. + * @private + */ + + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + + /** + * Module exports. + * @public + */ + + exports.charset = charset; + exports.charsets = { lookup: charset }; + exports.contentType = contentType; + exports.extension = extension; + exports.extensions = Object.create(null); + exports.lookup = lookup; + exports.types = Object.create(null); + + // Populate the extensions/types maps + populateMaps(exports.extensions, exports.types); + + /** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + + function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db[match[1].toLowerCase()]; + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false + } + + /** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + + function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str; + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime); + if (charset) mime += '; charset=' + charset.toLowerCase(); + } + + return mime + } + + /** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + + function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type); + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()]; + + if (!exts || !exts.length) { + return false + } + + return exts[0] + } + + /** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + + function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1); + + if (!extension) { + return false + } + + return exports.types[extension] || false + } - (function(self) { + /** + * Populate the extensions and types maps. + * @private + */ - if (self.fetch) { - return + function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana']; + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type]; + var exts = mime.extensions; + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts; + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i]; + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source); + var to = preference.indexOf(mime.source); + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type; + } + }); + } + } (mimeTypes)); + + var defer_1 = defer$1; + + /** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ + function defer$1(fn) + { + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof browser$1 == 'object' && typeof browser$1.nextTick == 'function' + ? browser$1.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); } + else + { + setTimeout(fn, 0); + } + } - var support = { - searchParams: 'URLSearchParams' in self, - iterable: 'Symbol' in self && 'iterator' in Symbol, - blob: 'FileReader' in self && 'Blob' in self && (function() { - try { - new Blob(); - return true - } catch(e) { - return false - } - })(), - formData: 'FormData' in self, - arrayBuffer: 'ArrayBuffer' in self + var defer = defer_1; + + // API + var async_1 = async$2; + + /** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ + function async$2(callback) + { + var isAsync = false; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } }; + } - if (support.arrayBuffer) { - var viewClasses = [ - '[object Int8Array]', - '[object Uint8Array]', - '[object Uint8ClampedArray]', - '[object Int16Array]', - '[object Uint16Array]', - '[object Int32Array]', - '[object Uint32Array]', - '[object Float32Array]', - '[object Float64Array]' - ]; - - var isDataView = function(obj) { - return obj && DataView.prototype.isPrototypeOf(obj) - }; + // API + var abort_1 = abort$2; - var isArrayBufferView = ArrayBuffer.isView || function(obj) { - return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 - }; + /** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ + function abort$2(state) + { + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; + } + + /** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ + function clean(key) + { + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); } + } + + var async$1 = async_1 + , abort$1 = abort_1 + ; + + // API + var iterate_1 = iterate$2; + + /** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ + function iterate$2(list, iterator, state, callback) + { + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } - function normalizeName(name) { - if (typeof name !== 'string') { - name = String(name); + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort$1(state); } - if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { - throw new TypeError('Invalid character in header field name') + else + { + state.results[key] = output; } - return name.toLowerCase() + + // return salvaged results + callback(error, state.results); + }); + } + + /** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ + function runJob(iterator, key, item, callback) + { + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async$1(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async$1(callback)); } - function normalizeValue(value) { - if (typeof value !== 'string') { - value = String(value); + return aborter; + } + + // API + var state_1 = state; + + /** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ + function state(list, sortMethod) + { + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length } - return value + ; + + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } + + return initState; + } + + var abort = abort_1 + , async = async_1 + ; + + // API + var terminator_1 = terminator$2; + + /** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ + function terminator$2(callback) + { + if (!Object.keys(this.jobs).length) + { + return; } - // Build a destructive iterator for the value list - function iteratorFor(items) { - var iterator = { - next: function() { - var value = items.shift(); - return {done: value === undefined, value: value} + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); + } + + var iterate$1 = iterate_1 + , initState$1 = state_1 + , terminator$1 = terminator_1 + ; + + // Public API + var parallel_1 = parallel; + + /** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ + function parallel(list, iterator, callback) + { + var state = initState$1(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate$1(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; } - }; - if (support.iterable) { - iterator[Symbol.iterator] = function() { - return iterator - }; - } + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); - return iterator + state.index++; } - function Headers(headers) { - this.map = {}; + return terminator$1.bind(state, callback); + } + + var serialOrdered$2 = {exports: {}}; + + var iterate = iterate_1 + , initState = state_1 + , terminator = terminator_1 + ; + + // Public API + serialOrdered$2.exports = serialOrdered$1; + // sorting helpers + serialOrdered$2.exports.ascending = ascending; + serialOrdered$2.exports.descending = descending; + + /** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ + function serialOrdered$1(list, iterator, sortMethod, callback) + { + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; - if (headers instanceof Headers) { - headers.forEach(function(value, name) { - this.append(name, value); - }, this); - } else if (Array.isArray(headers)) { - headers.forEach(function(header) { - this.append(header[0], header[1]); - }, this); - } else if (headers) { - Object.getOwnPropertyNames(headers).forEach(function(name) { - this.append(name, headers[name]); - }, this); + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); + } + + /* + * -- Sort methods + */ + + /** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ + function ascending(a, b) + { + return a < b ? -1 : a > b ? 1 : 0; + } + + /** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ + function descending(a, b) + { + return -1 * ascending(a, b); + } + + var serialOrderedExports = serialOrdered$2.exports; + + var serialOrdered = serialOrderedExports; + + // Public API + var serial_1 = serial; + + /** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ + function serial(list, iterator, callback) + { + return serialOrdered(list, iterator, null, callback); + } + + var asynckit$1 = + { + parallel : parallel_1, + serial : serial_1, + serialOrdered : serialOrderedExports + }; + + // populates missing values + var populate$1 = function(dst, src) { + + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; + }; + + var CombinedStream = combined_stream; + var util = require$$1; + var path = require$$2; + var http = require$$3; + var https = require$$4; + var parseUrl = require$$5.parse; + var fs = require$$6; + var Stream = require$$7.Stream; + var mime = mimeTypes; + var asynckit = asynckit$1; + var populate = populate$1; + + // Public API + var form_data = FormData$1; + + // make it a Stream + util.inherits(FormData$1, CombinedStream); + + /** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ + function FormData$1(options) { + if (!(this instanceof FormData$1)) { + return new FormData$1(options); } - Headers.prototype.append = function(name, value) { - name = normalizeName(name); - value = normalizeValue(value); - var oldValue = this.map[name]; - this.map[name] = oldValue ? oldValue+','+value : value; - }; + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; - Headers.prototype['delete'] = function(name) { - delete this.map[normalizeName(name)]; - }; + CombinedStream.call(this); - Headers.prototype.get = function(name) { - name = normalizeName(name); - return this.has(name) ? this.map[name] : null - }; + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } + } - Headers.prototype.has = function(name) { - return this.map.hasOwnProperty(normalizeName(name)) - }; + FormData$1.LINE_BREAK = '\r\n'; + FormData$1.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - Headers.prototype.set = function(name, value) { - this.map[normalizeName(name)] = normalizeValue(value); - }; + FormData$1.prototype.append = function(field, value, options) { - Headers.prototype.forEach = function(callback, thisArg) { - for (var name in this.map) { - if (this.map.hasOwnProperty(name)) { - callback.call(thisArg, this.map[name], name, this); - } + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } + + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); + }; + + FormData$1.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData$1.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } + }; + + FormData$1.prototype._lengthRetriever = function(value, callback) { + + if (value.hasOwnProperty('fd')) { + + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + + var fileSize; + + if (err) { + callback(err); + return; + } + + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); } - }; - Headers.prototype.keys = function() { - var items = []; - this.forEach(function(value, name) { items.push(name); }); - return iteratorFor(items) - }; + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - Headers.prototype.values = function() { - var items = []; - this.forEach(function(value) { items.push(value); }); - return iteratorFor(items) - }; + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); - Headers.prototype.entries = function() { - var items = []; - this.forEach(function(value, name) { items.push([name, value]); }); - return iteratorFor(items) + // something else + } else { + callback('Unknown stream'); + } + }; + + FormData$1.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) }; - if (support.iterable) { - Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); } - function consumed(body) { - if (body.bodyUsed) { - return Promise.reject(new TypeError('Already read')) + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData$1.LINE_BREAK; } - body.bodyUsed = true; } - function fileReaderReady(reader) { - return new Promise(function(resolve, reject) { - reader.onload = function() { - resolve(reader.result); - }; - reader.onerror = function() { - reject(reader.error); - }; - }) + return '--' + this.getBoundary() + FormData$1.LINE_BREAK + contents + FormData$1.LINE_BREAK; + }; + + FormData$1.prototype._getContentDisposition = function(value, options) { + + var filename + , contentDisposition + ; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); } - function readBlobAsArrayBuffer(blob) { - var reader = new FileReader(); - var promise = fileReaderReady(reader); - reader.readAsArrayBuffer(blob); - return promise + if (filename) { + contentDisposition = 'filename="' + filename + '"'; } - function readBlobAsText(blob) { - var reader = new FileReader(); - var promise = fileReaderReady(reader); - reader.readAsText(blob); - return promise + return contentDisposition; + }; + + FormData$1.prototype._getContentType = function(value, options) { + + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } - function readArrayBufferAsText(buf) { - var view = new Uint8Array(buf); - var chars = new Array(view.length); + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } - for (var i = 0; i < view.length; i++) { - chars[i] = String.fromCharCode(view[i]); - } - return chars.join('') + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; } - function bufferClone(buf) { - if (buf.slice) { - return buf.slice(0) - } else { - var view = new Uint8Array(buf.byteLength); - view.set(new Uint8Array(buf)); - return view.buffer - } - } - - function Body() { - this.bodyUsed = false; - - this._initBody = function(body) { - this._bodyInit = body; - if (!body) { - this._bodyText = ''; - } else if (typeof body === 'string') { - this._bodyText = body; - } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { - this._bodyBlob = body; - } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { - this._bodyFormData = body; - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this._bodyText = body.toString(); - } else if (support.arrayBuffer && support.blob && isDataView(body)) { - this._bodyArrayBuffer = bufferClone(body.buffer); - // IE 10-11 can't handle a DataView body. - this._bodyInit = new Blob([this._bodyArrayBuffer]); - } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { - this._bodyArrayBuffer = bufferClone(body); - } else { - throw new Error('unsupported BodyInit type') - } + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } - if (!this.headers.get('content-type')) { - if (typeof body === 'string') { - this.headers.set('content-type', 'text/plain;charset=UTF-8'); - } else if (this._bodyBlob && this._bodyBlob.type) { - this.headers.set('content-type', this._bodyBlob.type); - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); - } - } - }; + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData$1.DEFAULT_CONTENT_TYPE; + } - if (support.blob) { - this.blob = function() { - var rejected = consumed(this); - if (rejected) { - return rejected - } + return contentType; + }; - if (this._bodyBlob) { - return Promise.resolve(this._bodyBlob) - } else if (this._bodyArrayBuffer) { - return Promise.resolve(new Blob([this._bodyArrayBuffer])) - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as blob') - } else { - return Promise.resolve(new Blob([this._bodyText])) - } - }; + FormData$1.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData$1.LINE_BREAK; - this.arrayBuffer = function() { - if (this._bodyArrayBuffer) { - return consumed(this) || Promise.resolve(this._bodyArrayBuffer) - } else { - return this.blob().then(readBlobAsArrayBuffer) - } - }; + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); } - this.text = function() { - var rejected = consumed(this); - if (rejected) { - return rejected - } + next(footer); + }.bind(this); + }; - if (this._bodyBlob) { - return readBlobAsText(this._bodyBlob) - } else if (this._bodyArrayBuffer) { - return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as text') - } else { - return Promise.resolve(this._bodyText) - } - }; + FormData$1.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData$1.LINE_BREAK; + }; - if (support.formData) { - this.formData = function() { - return this.text().then(decode) - }; + FormData$1.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } + } - this.json = function() { - return this.text().then(JSON.parse) - }; + return formHeaders; + }; - return this + FormData$1.prototype.setBoundary = function(boundary) { + this._boundary = boundary; + }; + + FormData$1.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); } - // HTTP methods whose capitalization should be normalized - var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; + return this._boundary; + }; - function normalizeMethod(method) { - var upcased = method.toUpperCase(); - return (methods.indexOf(upcased) > -1) ? upcased : method - } + FormData$1.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); - function Request(input, options) { - options = options || {}; - var body = options.body; + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { - if (input instanceof Request) { - if (input.bodyUsed) { - throw new TypeError('Already read') + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); } - this.url = input.url; - this.credentials = input.credentials; - if (!options.headers) { - this.headers = new Headers(input.headers); - } - this.method = input.method; - this.mode = input.mode; - if (!body && input._bodyInit != null) { - body = input._bodyInit; - input.bodyUsed = true; + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData$1.LINE_BREAK)] ); } - } else { - this.url = String(input); } + } - this.credentials = options.credentials || this.credentials || 'omit'; - if (options.headers || !this.headers) { - this.headers = new Headers(options.headers); - } - this.method = normalizeMethod(options.method || this.method || 'GET'); - this.mode = options.mode || this.mode || null; - this.referrer = null; + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); + }; - if ((this.method === 'GET' || this.method === 'HEAD') && body) { - throw new TypeError('Body not allowed for GET or HEAD requests') - } - this._initBody(body); + FormData$1.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); } - Request.prototype.clone = function() { - return new Request(this, { body: this._bodyInit }) - }; + this._boundary = boundary; + }; - function decode(body) { - var form = new FormData(); - body.trim().split('&').forEach(function(bytes) { - if (bytes) { - var split = bytes.split('='); - var name = split.shift().replace(/\+/g, ' '); - var value = split.join('=').replace(/\+/g, ' '); - form.append(decodeURIComponent(name), decodeURIComponent(value)); - } - }); - return form + // Note: getLengthSync DOESN'T calculate streams length + // As workaround one can calculate file size manually + // and add it as knownLength option + FormData$1.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - function parseHeaders(rawHeaders) { - var headers = new Headers(); - rawHeaders.split(/\r?\n/).forEach(function(line) { - var parts = line.split(':'); - var key = parts.shift().trim(); - if (key) { - var value = parts.join(':').trim(); - headers.append(key, value); - } - }); - return headers + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); } - Body.call(Request.prototype); + return knownLength; + }; - function Response(bodyInit, options) { - if (!options) { - options = {}; - } + // Public API to check if length of added values is known + // https://github.com/form-data/form-data/issues/196 + // https://github.com/form-data/form-data/issues/262 + FormData$1.prototype.hasKnownLength = function() { + var hasKnownLength = true; - this.type = 'default'; - this.status = 'status' in options ? options.status : 200; - this.ok = this.status >= 200 && this.status < 300; - this.statusText = 'statusText' in options ? options.statusText : 'OK'; - this.headers = new Headers(options.headers); - this.url = options.url || ''; - this._initBody(bodyInit); + if (this._valuesToMeasure.length) { + hasKnownLength = false; } - Body.call(Response.prototype); + return hasKnownLength; + }; - Response.prototype.clone = function() { - return new Response(this._bodyInit, { - status: this.status, - statusText: this.statusText, - headers: new Headers(this.headers), - url: this.url - }) - }; + FormData$1.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - Response.error = function() { - var response = new Response(null, {status: 0, statusText: ''}); - response.type = 'error'; - return response - }; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } - var redirectStatuses = [301, 302, 303, 307, 308]; + if (!this._valuesToMeasure.length) { + browser$1.nextTick(cb.bind(this, null, knownLength)); + return; + } - Response.redirect = function(url, status) { - if (redirectStatuses.indexOf(status) === -1) { - throw new RangeError('Invalid status code') + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; } - return new Response(null, {status: status, headers: {location: url}}) - }; + values.forEach(function(length) { + knownLength += length; + }); - self.Headers = Headers; - self.Request = Request; - self.Response = Response; + cb(null, knownLength); + }); + }; - self.fetch = function(input, init) { - return new Promise(function(resolve, reject) { - var request = new Request(input, init); - var xhr = new XMLHttpRequest(); + FormData$1.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; - xhr.onload = function() { - var options = { - status: xhr.status, - statusText: xhr.statusText, - headers: parseHeaders(xhr.getAllResponseHeaders() || '') - }; - options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); - var body = 'response' in xhr ? xhr.response : xhr.responseText; - resolve(new Response(body, options)); - }; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { - xhr.onerror = function() { - reject(new TypeError('Network request failed')); - }; + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); - xhr.ontimeout = function() { - reject(new TypeError('Network request failed')); - }; + // use custom params + } else { - xhr.open(request.method, request.url, true); + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } - if (request.credentials === 'include') { - xhr.withCredentials = true; - } + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); - if ('responseType' in xhr && support.blob) { - xhr.responseType = 'blob'; - } + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } - request.headers.forEach(function(value, name) { - xhr.setRequestHeader(name, value); - }); + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } - xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); - }) - }; - self.fetch.polyfill = true; - })(typeof self !== 'undefined' ? self : commonjsGlobal); + // add content length + if (length) { + request.setHeader('Content-Length', length); + } + + this.pipe(request); + if (cb) { + var onResponse; + + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + + return cb.call(this, error, responce); + }; + + onResponse = callback.bind(this, null); + + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); + + return request; + }; + + FormData$1.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } + }; - var browser = {}; + FormData$1.prototype.toString = function () { + return '[object FormData]'; + }; - browser.atob = self.atob.bind(self); - browser.btoa = self.btoa.bind(self); + commonjsGlobal.FormData = form_data; /** * @@ -791,7 +20150,7 @@ sap.ui.define((function () { 'use strict'; })(); Object.defineProperty(exports, "__esModule", { value: true }); - var isomorphic_base64_1 = browser; + var isomorphic_base64_1 = browser$2; (function (cmis) { var Buffer = commonjsGlobal['Buffer']; var Options = (function () { 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 37d8e8b92..bec9b7e75 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 @@ -151,207 +151,6 @@ sap.ui.define((function () { 'use strict'; return (!isTablet() && !isPhone()) || isWindows8OrAbove(); }; - /** - * @license - * Copyright 2023 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */ - /** - * Map of ARIAMixin properties to attributes - */ - // Shim the global element internals object - // Methods should be fine as noops and properties can generally - // be while on the server. - const ElementInternalsShim = class ElementInternals { - get shadowRoot() { - // Grab the shadow root instance from the Element shim - // to ensure that the shadow root is always available - // to the internals instance even if the mode is 'closed' - return this.__host - .__shadowRoot; - } - constructor(_host) { - this.ariaAtomic = ''; - this.ariaAutoComplete = ''; - this.ariaBrailleLabel = ''; - this.ariaBrailleRoleDescription = ''; - this.ariaBusy = ''; - this.ariaChecked = ''; - this.ariaColCount = ''; - this.ariaColIndex = ''; - this.ariaColSpan = ''; - this.ariaCurrent = ''; - this.ariaDescription = ''; - this.ariaDisabled = ''; - this.ariaExpanded = ''; - this.ariaHasPopup = ''; - this.ariaHidden = ''; - this.ariaInvalid = ''; - this.ariaKeyShortcuts = ''; - this.ariaLabel = ''; - this.ariaLevel = ''; - this.ariaLive = ''; - this.ariaModal = ''; - this.ariaMultiLine = ''; - this.ariaMultiSelectable = ''; - this.ariaOrientation = ''; - this.ariaPlaceholder = ''; - this.ariaPosInSet = ''; - this.ariaPressed = ''; - this.ariaReadOnly = ''; - this.ariaRequired = ''; - this.ariaRoleDescription = ''; - this.ariaRowCount = ''; - this.ariaRowIndex = ''; - this.ariaRowSpan = ''; - this.ariaSelected = ''; - this.ariaSetSize = ''; - this.ariaSort = ''; - this.ariaValueMax = ''; - this.ariaValueMin = ''; - this.ariaValueNow = ''; - this.ariaValueText = ''; - this.role = ''; - this.form = null; - this.labels = []; - this.states = new Set(); - this.validationMessage = ''; - this.validity = {}; - this.willValidate = true; - this.__host = _host; - } - checkValidity() { - // TODO(augustjk) Consider actually implementing logic. - // See https://github.com/lit/lit/issues/3740 - console.warn('`ElementInternals.checkValidity()` was called on the server.' + - 'This method always returns true.'); - return true; - } - reportValidity() { - return true; - } - setFormValue() { } - setValidity() { } - }; - - const attributes = new WeakMap(); - const attributesForElement = element => { - let attrs = attributes.get(element); - if (attrs === undefined) { - attributes.set(element, attrs = new Map()); - } - return attrs; - }; - const ElementShim = class Element { - constructor() { - this.__shadowRootMode = null; - this.__shadowRoot = null; - this.__internals = null; - } - get attributes() { - return Array.from(attributesForElement(this)).map(([name, value]) => ({ - name, - value - })); - } - get shadowRoot() { - if (this.__shadowRootMode === "closed") { - return null; - } - return this.__shadowRoot; - } - get localName() { - return this.constructor.__localName; - } - get tagName() { - return this.localName?.toUpperCase(); - } - setAttribute(name, value) { - attributesForElement(this).set(name, String(value)); - } - removeAttribute(name) { - attributesForElement(this).delete(name); - } - toggleAttribute(name, force) { - if (this.hasAttribute(name)) { - if (force === undefined || !force) { - this.removeAttribute(name); - return false; - } - } else { - if (force === undefined || force) { - this.setAttribute(name, ""); - return true; - } else { - return false; - } - } - return true; - } - hasAttribute(name) { - return attributesForElement(this).has(name); - } - attachShadow(init) { - const shadowRoot = { - host: this - }; - this.__shadowRootMode = init.mode; - if (init && init.mode === "open") { - this.__shadowRoot = shadowRoot; - } - return shadowRoot; - } - attachInternals() { - if (this.__internals !== null) { - throw new Error(`Failed to execute 'attachInternals' on 'HTMLElement': ` + `ElementInternals for the specified element was already attached.`); - } - const internals = new ElementInternalsShim(this); - this.__internals = internals; - return internals; - } - getAttribute(name) { - const value = attributesForElement(this).get(name); - return value ?? null; - } - }; - const ElementShimWithRealType = ElementShim; - const HTMLElementShim = class HTMLElement extends ElementShim {}; - const HTMLElementShimWithRealType = HTMLElementShim; - const CustomElementRegistryShim = class CustomElementRegistry { - constructor() { - this.__definitions = new Map(); - } - define(name, ctor) { - if (this.__definitions.has(name)) { - { - throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': ` + `the name "${name}" has already been used with this registry`); - } - } - ctor.__localName = name; - this.__definitions.set(name, { - ctor, - observedAttributes: ctor.observedAttributes ?? [] - }); - } - get(name) { - const definition = this.__definitions.get(name); - return definition?.ctor; - } - }; - const CustomElementRegistryShimWithRealType = CustomElementRegistryShim; - const customElements$1 = new CustomElementRegistryShimWithRealType(); - - /* eslint-disable max-classes-per-file */ - globalThis.HTMLElement ??= HTMLElementShimWithRealType; - globalThis.Element ??= ElementShimWithRealType; - globalThis.customElements ??= customElements$1; - class NodeShim { - } - globalThis.Node ??= NodeShim; - class FileListShim { - } - globalThis.FileList ??= FileListShim; - var class2type = {}; var hasOwn = class2type.hasOwnProperty; var toString = class2type.toString; @@ -3011,7 +2810,7 @@ sap.ui.define((function () { 'use strict'; * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - var t$1;const i$1=globalThis,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=void 0===i$1.document?{createTreeWalker:()=>({})}: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,x=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),T=x(1),b=x(2),w=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 x=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+x):s+n+(-2===v?(e.push(void 0),i):x);}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!==w,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 k(i.insertBefore(u$1(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; + 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}; /** * @license @@ -3024,20 +2823,20 @@ sap.ui.define((function () { 'use strict'; * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const {I:l$1}=Z,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$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;}}; /** * @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$1=0,A=p$1.length-1;for(;j<=k&&w$1<=A;)if(null===a$1[j])j++;else if(null===a$1[k])k--;else if(h[j]===v[w$1])m$1[w$1]=f(a$1[j],p$1[w$1]),j++,w$1++;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$1])m$1[w$1]=f(a$1[k],p$1[w$1]),c$1(s,a$1[j],a$1[k]),k--,w$1++;else if(void 0===y&&(y=u(v,w$1,A),x=u(h,j,k)),y.has(h[j]))if(y.has(h[k])){const e=x.get(v[w$1]),t=void 0!==e?a$1[e]:null;if(null===t){const e=c$1(s,a$1[j]);f(e,p$1[w$1]),m$1[w$1]=e;}else m$1[w$1]=f(t,p$1[w$1]),c$1(s,a$1[j],t),a$1[e]=null;w$1++;}else p(a$1[k]),k--;else p(a$1[j]),j++;for(;w$1<=A;){const e=c$1(s,m$1[A+1]);f(e,p$1[w$1]),m$1[w$1++]=e;}for(;j<=k;){const e=a$1[j++];null!==e&&p(e);}return this.ut=v,a(s,m$1),w}}); + 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}}); /** * @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 w}}); + */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}}); /** * @license @@ -3049,11 +2848,11 @@ sap.ui.define((function () { 'use strict'; * @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===w)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{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; const effectiveHtml = (strings, ...values) => { const litStatic = getFeature("LitStatic"); - const fn = litStatic ? litStatic.html : T; + const fn = litStatic ? litStatic.html : x; return fn(strings, ...values); }; const effectiveSvg = (strings, ...values) => { @@ -3066,7 +2865,7 @@ sap.ui.define((function () { 'use strict'; if (openUI5Enablement) { templateResult = openUI5Enablement.wrapTemplateResultInBusyMarkup(effectiveHtml, options.host, templateResult); } - B(templateResult, container, options); + D(templateResult, container, options); }; const scopeTag = (tag, tags, suffix) => { const litStatic = getFeature("LitStatic"); 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 07824e96c..70812e7f6 100644 --- a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/app.js +++ b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/firebase/app.js @@ -1,4 +1,4 @@ -sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (index_esm2017) { 'use strict'; +sap.ui.define(['ui5/ecosystem/demo/app/resources/index.cjs3'], (function (index_cjs$1) { 'use strict'; var index_cjs = {}; @@ -6,7 +6,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind Object.defineProperty(exports, '__esModule', { value: true }); - var app = index_esm2017.require$$0; + var app = index_cjs$1.index_cjs; var name = "firebase"; var version = "10.13.1"; 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 7e07ed47a..b605ef988 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,4 +1,4 @@ -sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (index_esm2017) { 'use strict'; +sap.ui.define(['ui5/ecosystem/demo/app/resources/index.cjs3'], (function (index_cjs$1) { 'use strict'; var index_cjs = {}; @@ -239,7 +239,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind * 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_esm2017.global.TYPED_ARRAY_SUPPORT !== undefined ? index_esm2017.global.TYPED_ARRAY_SUPPORT : true; + 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. @@ -1947,8 +1947,6 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var index_node_cjs = {}; - var require$$1$5 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(index_esm2017.index_esm2017); - var inherits; if (typeof Object.create === 'function'){ inherits = function inherits(ctor, superCtor) { @@ -2031,22 +2029,22 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind // 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_esm2017.global.process)) { + if (isUndefined(index_cjs$1.global.process)) { return function () { return deprecate(fn, msg).apply(this, arguments); }; } - if (index_esm2017.browser$1.noDeprecation === true) { + if (index_cjs$1.browser$1.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { - if (index_esm2017.browser$1.throwDeprecation) { + if (index_cjs$1.browser$1.throwDeprecation) { throw new Error(msg); - } else if (index_esm2017.browser$1.traceDeprecation) { + } else if (index_cjs$1.browser$1.traceDeprecation) { console.trace(msg); } else { console.error(msg); @@ -2062,7 +2060,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var debugs = {}; var debugEnviron; function debuglog(set) { - if (isUndefined(debugEnviron)) debugEnviron = index_esm2017.browser$1.env.NODE_DEBUG || ""; + 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)) { @@ -2601,10 +2599,10 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args).then( function (ret) { - index_esm2017.browser$1.nextTick(cb.bind(null, null, ret)); + index_cjs$1.browser$1.nextTick(cb.bind(null, null, ret)); }, function (rej) { - index_esm2017.browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); + index_cjs$1.browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); } ); } @@ -2686,9 +2684,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind types: types }); - var require$$3$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_util); - - var require$$4$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(index_esm2017.index_esm2017$1); + var require$$3$1 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_util); var undici$1 = {}; @@ -2742,7 +2738,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (isBuffer$3(arrbuf)) { return false; } - if (typeof index_esm2017.global.ArrayBuffer !== 'function') { + if (typeof index_cjs$1.global.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { @@ -3171,7 +3167,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind throws: throws }); - var require$$1$4 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_assert); + var require$$1$4 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_assert); var _polyfillNode_net = {}; @@ -3180,9 +3176,9 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind default: _polyfillNode_net }); - var require$$1$3 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_net$1); + var require$$1$3 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_net$1); - var hasFetch = isFunction(index_esm2017.global.fetch) && isFunction(index_esm2017.global.ReadableStream); + var hasFetch = isFunction(index_cjs$1.global.fetch) && isFunction(index_cjs$1.global.ReadableStream); var _blobConstructor; function blobConstructor() { @@ -3190,7 +3186,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind return _blobConstructor; } try { - new index_esm2017.global.Blob([new ArrayBuffer(1)]); + new index_cjs$1.global.Blob([new ArrayBuffer(1)]); _blobConstructor = true; } catch (e) { _blobConstructor = false; @@ -3201,10 +3197,10 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind function checkTypeSupport(type) { if (!xhr) { - xhr = new index_esm2017.global.XMLHttpRequest(); + xhr = new index_cjs$1.global.XMLHttpRequest(); // If location.host is empty, e.g. if this page/worker was loaded // from a Blob, then use example.com to avoid an error - xhr.open('GET', index_esm2017.global.location.host ? '/' : 'https://example.com'); + xhr.open('GET', index_cjs$1.global.location.host ? '/' : 'https://example.com'); } try { xhr.responseType = type; @@ -3217,8 +3213,8 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. // Safari 7.1 appears to have fixed this bug. - var haveArrayBuffer = typeof index_esm2017.global.ArrayBuffer !== 'undefined'; - var haveSlice = haveArrayBuffer && isFunction(index_esm2017.global.ArrayBuffer.prototype.slice); + var haveArrayBuffer = typeof index_cjs$1.global.ArrayBuffer !== 'undefined'; + var haveSlice = haveArrayBuffer && isFunction(index_cjs$1.global.ArrayBuffer.prototype.slice); var arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer'); // These next two tests unavoidably show warnings in Chrome. Since fetch will always @@ -3227,7 +3223,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var mozchunkedarraybuffer = !hasFetch && haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer'); var overrideMimeType = isFunction(xhr.overrideMimeType); - var vbArray = isFunction(index_esm2017.global.VBArray); + var vbArray = isFunction(index_cjs$1.global.VBArray); function isFunction(value) { return typeof value === 'function' @@ -4365,7 +4361,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; - if (state.sync) index_esm2017.nextTick(emitReadable_, stream);else emitReadable_(stream); + if (state.sync) index_cjs$1.nextTick(emitReadable_, stream);else emitReadable_(stream); } } @@ -4384,7 +4380,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; - index_esm2017.nextTick(maybeReadMore_, stream, state); + index_cjs$1.nextTick(maybeReadMore_, stream, state); } } @@ -4429,7 +4425,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var doEnd = (!pipeOpts || pipeOpts.end !== false); var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) index_esm2017.nextTick(endFn);else src.once('end', endFn); + if (state.endEmitted) index_cjs$1.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable) { @@ -4615,7 +4611,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { - index_esm2017.nextTick(nReadingNextTick, this); + index_cjs$1.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } @@ -4646,7 +4642,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind function resume$1(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; - index_esm2017.nextTick(resume_, stream, state); + index_cjs$1.nextTick(resume_, stream, state); } } @@ -4854,7 +4850,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (!state.endEmitted) { state.ended = true; - index_esm2017.nextTick(endReadableNT, state, stream); + index_cjs$1.nextTick(endReadableNT, state, stream); } } @@ -5032,7 +5028,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); - index_esm2017.nextTick(cb, er); + index_cjs$1.nextTick(cb, er); } // If we get something that is not a buffer, string, null, or undefined, @@ -5053,7 +5049,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind } if (er) { stream.emit('error', er); - index_esm2017.nextTick(cb, er); + index_cjs$1.nextTick(cb, er); valid = false; } return valid; @@ -5153,7 +5149,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; - if (sync) index_esm2017.nextTick(cb, er);else cb(er); + if (sync) index_cjs$1.nextTick(cb, er);else cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); @@ -5183,7 +5179,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (sync) { /**/ - index_esm2017.nextTick(afterWrite, stream, state, finished, cb); + index_cjs$1.nextTick(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); @@ -5325,7 +5321,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind state.ending = true; finishMaybe(stream, state); if (cb) { - if (state.finished) index_esm2017.nextTick(cb);else stream.once('finish', cb); + if (state.finished) index_cjs$1.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; @@ -5387,7 +5383,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind // no more data can be written. // But allow more writes to happen in this tick. - index_esm2017.nextTick(onEndNT, this); + index_cjs$1.nextTick(onEndNT, this); } function onEndNT(self) { @@ -5705,7 +5701,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind // Fake the 'close' event, but only once 'end' fires self.on('end', function() { // The nextTick is necessary to prevent the 'request' module from causing an infinite loop - index_esm2017.browser$1.nextTick(function() { + index_cjs$1.browser$1.nextTick(function() { self.emit('close'); }); }); @@ -5797,7 +5793,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind break try { // This fails in IE8 - response = new index_esm2017.global.VBArray(xhr.responseBody).toArray(); + response = new index_cjs$1.global.VBArray(xhr.responseBody).toArray(); } catch (e) { // pass } @@ -5843,7 +5839,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind response = xhr.response; if (xhr.readyState !== rStates.LOADING) break - var reader = new index_esm2017.global.MSStreamReader(); + var reader = new index_cjs$1.global.MSStreamReader(); reader.onprogress = function() { if (reader.result.byteLength > self._pos) { self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))); @@ -6008,7 +6004,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var body; if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { if (blobConstructor()) { - body = new index_esm2017.global.Blob(self._body.map(function(buffer) { + body = new index_cjs$1.global.Blob(self._body.map(function(buffer) { return toArrayBuffer(buffer) }), { type: (headersObj['content-type'] || {}).value || '' @@ -6024,7 +6020,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind return [headersObj[name].name, headersObj[name].value] }); - index_esm2017.global.fetch(self._opts.url, { + index_cjs$1.global.fetch(self._opts.url, { method: self._opts.method, headers: headers, body: body, @@ -6037,11 +6033,11 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind self.emit('error', reason); }); } else { - var xhr = self._xhr = new index_esm2017.global.XMLHttpRequest(); + var xhr = self._xhr = new index_cjs$1.global.XMLHttpRequest(); try { xhr.open(self._opts.method, self._opts.url, true); } catch (err) { - index_esm2017.browser$1.nextTick(function() { + index_cjs$1.browser$1.nextTick(function() { self.emit('error', err); }); return @@ -6087,7 +6083,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind try { xhr.send(body); } catch (err) { - index_esm2017.browser$1.nextTick(function() { + index_cjs$1.browser$1.nextTick(function() { self.emit('error', err); }); return @@ -6608,8 +6604,8 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind }); // WHATWG API - const URL$2 = index_esm2017.global.URL; - const URLSearchParams$1 = index_esm2017.global.URLSearchParams; + const URL$2 = index_cjs$1.global.URL; + const URLSearchParams$1 = index_cjs$1.global.URLSearchParams; var _polyfillNode_url = { parse: urlParse, resolve: urlResolve, @@ -7376,7 +7372,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind // Normally, the page is loaded from http or https, so not specifying a protocol // will result in a (valid) protocol-relative url. However, this won't work if // the protocol is something else, like 'file:' - var defaultProtocol = index_esm2017.global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''; + var defaultProtocol = index_cjs$1.global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''; var protocol = opts.protocol || defaultProtocol; var host = opts.hostname || opts.host; @@ -7514,7 +7510,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind request: request$3 }); - var require$$15 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_http$1); + var require$$15 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_http$1); var symbols$4 = { kClose: Symbol('close'), @@ -7584,13 +7580,13 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind kHttpsProxyAgent: Symbol('https proxy agent') }; - var require$$0$2 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_stream); + var require$$0$2 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_stream); - var require$$29 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_buffer); + var require$$29 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_buffer); - var require$$7$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_querystring$1); + var require$$7$1 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_querystring$1); - var require$$9 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_events); + var require$$9 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_events); let UndiciError$2 = class UndiciError extends Error { constructor (message) { @@ -8815,7 +8811,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind channel: channel }); - var require$$0$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_diagnostics_channel); + var require$$0$1 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_diagnostics_channel); const diagnosticsChannel = require$$0$1; const util$o = require$$3$1; @@ -9674,7 +9670,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind default: _polyfillNode_tls }); - var require$$4 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_tls$1); + var require$$4 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_tls$1); const net$1 = require$$1$3; const assert$d = require$$1$4; @@ -9691,12 +9687,12 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind let SessionCache; // FIXME: remove workaround when the Node bug is fixed // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 - if (index_esm2017.commonjsGlobal.FinalizationRegistry && !(index_esm2017.browser$1.env.NODE_V8_COVERAGE || index_esm2017.browser$1.env.UNDICI_NO_FG)) { + if (index_cjs$1.commonjsGlobal.FinalizationRegistry && !(index_cjs$1.browser$1.env.NODE_V8_COVERAGE || index_cjs$1.browser$1.env.UNDICI_NO_FG)) { SessionCache = class WeakSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions; this._sessionCache = new Map(); - this._sessionRegistry = new index_esm2017.commonjsGlobal.FinalizationRegistry((key) => { + this._sessionRegistry = new index_cjs$1.commonjsGlobal.FinalizationRegistry((key) => { if (this._sessionCache.size < this._maxCachedSessions) { return } @@ -9843,7 +9839,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind const timeoutId = setTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { - if (index_esm2017.browser$1.platform === 'win32') { + if (index_cjs$1.browser$1.platform === 'win32') { // Windows needs an extra setImmediate probably due to implementation differences in the socket logic s2 = setImmediate(() => onConnectTimeout()); } else { @@ -15734,7 +15730,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind this.write_in_progress = true; var self = this; - index_esm2017.browser$1.nextTick(function() { + index_cjs$1.browser$1.nextTick(function() { self.write_in_progress = false; var res = self._write(flush, input, in_off, in_len, out, out_off, out_len); self.callback(res[0], res[1]); @@ -16280,7 +16276,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind } }); } else { - index_esm2017.browser$1.nextTick(callback); + index_cjs$1.browser$1.nextTick(callback); } }; @@ -16303,7 +16299,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind } if (ws.ended) { - if (callback) index_esm2017.browser$1.nextTick(callback); + if (callback) index_cjs$1.browser$1.nextTick(callback); } else if (ws.ending) { if (callback) this.once("end", callback); } else if (ws.needDrain) { @@ -16318,7 +16314,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind }; Zlib.prototype.close = function (callback) { - if (callback) index_esm2017.browser$1.nextTick(callback); + if (callback) index_cjs$1.browser$1.nextTick(callback); if (this._closed) return; @@ -16327,7 +16323,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind this._binding.close(); var self = this; - index_esm2017.browser$1.nextTick(function () { + index_cjs$1.browser$1.nextTick(function () { self.emit("close"); }); }; @@ -16534,7 +16530,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind unzipSync: unzipSync }); - var require$$0 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_zlib$1); + var require$$0 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_zlib$1); var constants$4; var hasRequiredConstants$2; @@ -17466,13 +17462,13 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind default: _polyfillNode_perf_hooks }); - var require$$5$2 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_perf_hooks$1); + var require$$5$2 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_perf_hooks$1); var types_polyfillNodeIgnore = /*#__PURE__*/Object.freeze({ __proto__: null }); - var require$$7 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(types_polyfillNodeIgnore); + var require$$7 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(types_polyfillNodeIgnore); var webidl_1; var hasRequiredWebidl; @@ -18182,7 +18178,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind default: _polyfillNode_crypto }); - var require$$6 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_crypto$1); + var require$$6 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_crypto$1); var util$m; var hasRequiredUtil$5; @@ -21259,7 +21255,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind let extractBody; async function lazyllhttp () { - const llhttpWasmData = index_esm2017.browser$1.env.JEST_WORKER_ID ? requireLlhttpWasm() : undefined; + const llhttpWasmData = index_cjs$1.browser$1.env.JEST_WORKER_ID ? requireLlhttpWasm() : undefined; let mod; try { @@ -22086,7 +22082,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind return false } - index_esm2017.browser$1.emitWarning(new RequestContentLengthMismatchError$1()); + index_cjs$1.browser$1.emitWarning(new RequestContentLengthMismatchError$1()); } const socket = client[kSocket$1]; @@ -22442,7 +22438,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind throw new RequestContentLengthMismatchError$1() } - index_esm2017.browser$1.emitWarning(new RequestContentLengthMismatchError$1()); + index_cjs$1.browser$1.emitWarning(new RequestContentLengthMismatchError$1()); } socket.cork(); @@ -22516,7 +22512,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (client[kStrictContentLength$2]) { throw new RequestContentLengthMismatchError$1() } else { - index_esm2017.browser$1.emitWarning(new RequestContentLengthMismatchError$1()); + index_cjs$1.browser$1.emitWarning(new RequestContentLengthMismatchError$1()); } } @@ -22559,7 +22555,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind constants: constants$2 }); - var require$$5$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_http2); + var require$$5$1 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_http2); const assert$a = require$$1$4; const { pipeline: pipeline$1 } = require$$0$2; @@ -22639,7 +22635,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (!h2ExperimentalWarned) { h2ExperimentalWarned = true; - index_esm2017.browser$1.emitWarning('H2 support is experimental, expect them to change at any time.', { + index_cjs$1.browser$1.emitWarning('H2 support is experimental, expect them to change at any time.', { code: 'UNDICI-H2' }); } @@ -22929,7 +22925,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind return false } - index_esm2017.browser$1.emitWarning(new RequestContentLengthMismatchError()); + index_cjs$1.browser$1.emitWarning(new RequestContentLengthMismatchError()); } if (contentLength != null) { @@ -23696,7 +23692,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind this[kInterceptors$4] = interceptors.Client; if (!deprecatedInterceptorWarned) { deprecatedInterceptorWarned = true; - index_esm2017.browser$1.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', { + index_cjs$1.browser$1.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', { code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED' }); } @@ -24850,7 +24846,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind var agent = Agent$5; - var require$$1$2 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_url$1); + var require$$1$2 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_url$1); const { kProxy, kClose: kClose$3, kDestroy: kDestroy$1, kInterceptors } = symbols$4; const { URL: URL$1 } = require$$1$2; @@ -25064,7 +25060,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind if (!experimentalWarned) { experimentalWarned = true; - index_esm2017.browser$1.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', { + index_cjs$1.browser$1.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', { code: 'UNDICI-EHPA' }); } @@ -25073,14 +25069,14 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind this[kNoProxyAgent] = new Agent$3(agentOpts); - const HTTP_PROXY = httpProxy ?? index_esm2017.browser$1.env.http_proxy ?? index_esm2017.browser$1.env.HTTP_PROXY; + const HTTP_PROXY = httpProxy ?? index_cjs$1.browser$1.env.http_proxy ?? index_cjs$1.browser$1.env.HTTP_PROXY; if (HTTP_PROXY) { this[kHttpProxyAgent] = new ProxyAgent$1({ ...agentOpts, uri: HTTP_PROXY }); } else { this[kHttpProxyAgent] = this[kNoProxyAgent]; } - const HTTPS_PROXY = httpsProxy ?? index_esm2017.browser$1.env.https_proxy ?? index_esm2017.browser$1.env.HTTPS_PROXY; + const HTTPS_PROXY = httpsProxy ?? index_cjs$1.browser$1.env.https_proxy ?? index_cjs$1.browser$1.env.HTTPS_PROXY; if (HTTPS_PROXY) { this[kHttpsProxyAgent] = new ProxyAgent$1({ ...agentOpts, uri: HTTPS_PROXY }); } else { @@ -25194,7 +25190,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind } get #noProxyEnv () { - return index_esm2017.browser$1.env.no_proxy ?? index_esm2017.browser$1.env.NO_PROXY ?? '' + return index_cjs$1.browser$1.env.no_proxy ?? index_cjs$1.browser$1.env.NO_PROXY ?? '' } }; @@ -26061,7 +26057,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind AsyncResource: AsyncResource$5 }); - var require$$1$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_async_hooks); + var require$$1$1 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_async_hooks); const assert$4 = require$$1$4; const { Readable: Readable$1 } = readable; @@ -27718,7 +27714,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind function noop(){} - var _polyfillNode_console = index_esm2017.global.console ? index_esm2017.global.console : { + var _polyfillNode_console = index_cjs$1.global.console ? index_cjs$1.global.console : { log: noop, info: noop, warn: noop, @@ -27735,13 +27731,13 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind default: _polyfillNode_console }); - var require$$1 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_console$1); + var require$$1 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_console$1); const { Transform } = require$$0$2; const { Console } = require$$1; - const PERSISTENT = index_esm2017.browser$1.versions.icu ? '✅' : 'Y '; - const NOT_PERSISTENT = index_esm2017.browser$1.versions.icu ? '❌' : 'N '; + const PERSISTENT = index_cjs$1.browser$1.versions.icu ? '✅' : 'Y '; + const NOT_PERSISTENT = index_cjs$1.browser$1.versions.icu ? '❌' : 'N '; /** * Gets the output of `console.table(…)` as a string. @@ -27757,7 +27753,7 @@ sap.ui.define(['ui5/ecosystem/demo/app/resources/index.esm2017'], (function (ind this.logger = new Console({ stdout: this.transform, inspectOptions: { - colors: !disableColors && !index_esm2017.browser$1.env.CI + colors: !disableColors && !index_cjs$1.browser$1.env.CI } }); } @@ -28905,7 +28901,7 @@ ${pendingInterceptorsFormatter.format(pending)} const textEncoder = new TextEncoder('utf-8'); - const hasFinalizationRegistry = globalThis.FinalizationRegistry && index_esm2017.browser$1.version.indexOf('v18') !== 0; + const hasFinalizationRegistry = globalThis.FinalizationRegistry && index_cjs$1.browser$1.version.indexOf('v18') !== 0; let registry; if (hasFinalizationRegistry) { @@ -29537,8 +29533,8 @@ ${pendingInterceptorsFormatter.format(pending)} dispatcherWeakref = function () { // FIXME: remove workaround when the Node bug is backported to v18 // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 - if (index_esm2017.browser$1.env.NODE_V8_COVERAGE && index_esm2017.browser$1.version.startsWith('v18')) { - index_esm2017.browser$1._rawDebug('Using compatibility WeakRef and FinalizationRegistry'); + if (index_cjs$1.browser$1.env.NODE_V8_COVERAGE && index_cjs$1.browser$1.version.startsWith('v18')) { + index_cjs$1.browser$1._rawDebug('Using compatibility WeakRef and FinalizationRegistry'); return { WeakRef: CompatWeakRef, FinalizationRegistry: CompatFinalizer @@ -29929,7 +29925,7 @@ ${pendingInterceptorsFormatter.format(pending)} } if (!patchMethodWarning && request.method === 'patch') { - index_esm2017.browser$1.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { + index_cjs$1.browser$1.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { code: 'UNDICI-FETCH-patch' }); @@ -33179,7 +33175,7 @@ ${pendingInterceptorsFormatter.format(pending)} return encoding; } - var require$$5 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(_polyfillNode_string_decoder); + var require$$5 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(_polyfillNode_string_decoder); var util$7; var hasRequiredUtil$4; @@ -35853,7 +35849,7 @@ ${pendingInterceptorsFormatter.format(pending)} __proto__: null }); - var require$$3 = /*@__PURE__*/index_esm2017.getAugmentedNamespace(worker_threads_polyfillNodeIgnore); + var require$$3 = /*@__PURE__*/index_cjs$1.getAugmentedNamespace(worker_threads_polyfillNodeIgnore); var events; var hasRequiredEvents; @@ -36567,7 +36563,7 @@ ${pendingInterceptorsFormatter.format(pending)} } // https://nodejs.org/api/intl.html#detecting-internationalization-support - const hasIntl = typeof index_esm2017.browser$1.versions.icu === 'string'; + const hasIntl = typeof index_cjs$1.browser$1.versions.icu === 'string'; const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined; /** @@ -38868,7 +38864,7 @@ ${pendingInterceptorsFormatter.format(pending)} if (!experimentalWarned) { experimentalWarned = true; - index_esm2017.browser$1.emitWarning('EventSource is experimental, expect them to change at any time.', { + index_cjs$1.browser$1.emitWarning('EventSource is experimental, expect them to change at any time.', { code: 'UNDICI-ES' }); } @@ -39406,11 +39402,11 @@ ${pendingInterceptorsFormatter.format(pending)} Object.defineProperty(index_node_cjs, '__esModule', { value: true }); - var app = index_esm2017.require$$0; - var component = require$$1$5; - var logger = index_esm2017.index_cjs; + 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$1; - var util = require$$4$1; + var util = index_cjs$1.require$$4; var undici = undici$1; var crypto = require$$6; diff --git a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.esm2017.js b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.cjs3.js similarity index 58% rename from packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.esm2017.js rename to packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.cjs3.js index 6825cb32e..64039c115 100644 --- a/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.esm2017.js +++ b/packages/ui5-tooling-modules/test/__snap__/3fe099fa/index.cjs3.js @@ -27,2314 +27,2372 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return a; } - 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 index_cjs$2 = {}; - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; + var index_cjs$1 = {}; - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } + var tslib$1 = {exports: {}}; - function drainQueue() { - if (draining) { - return; + (function (module) { + var __extends; + var __assign; + var __rest; + var __decorate; + var __param; + var __esDecorate; + var __runInitializers; + var __propKey; + var __setFunctionName; + var __metadata; + var __awaiter; + var __generator; + var __exportStar; + var __values; + var __read; + var __spread; + var __spreadArrays; + var __spreadArray; + var __await; + var __asyncGenerator; + var __asyncDelegator; + var __asyncValues; + var __makeTemplateObject; + var __importStar; + var __importDefault; + var __classPrivateFieldGet; + var __classPrivateFieldSet; + var __classPrivateFieldIn; + var __createBinding; + var __addDisposableResource; + var __disposeResources; + (function (factory) { + var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {}; + { + factory(createExporter(root, createExporter(module.exports))); } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { + value: true + }); + } else { + exports.__esModule = true; } - queueIndex = -1; - len = queue.length; + } + return function (id, v) { + return exports[id] = previous ? previous(id, v) : v; + }; } - 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$2 = ''; // 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$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 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; + })(function (exporter) { + var 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]; + }); + __extends = 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 __()); + }; + __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; + }); + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + }; + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return (c > 3 && r && Object.defineProperty(target, key, r), r); + }; + __param = function (paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; + }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { + get: descriptor.get, + set: descriptor.set + } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } - 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(); + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } - 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 useValue ? value : void 0; + }; + __propKey = function (x) { + return typeof x === "symbol" ? x : ("").concat(x); + }; + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? ("[").concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { + configurable: true, + value: prefix ? ("").concat(prefix, " ", name) : name + }); + }; + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); } - } - 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; + 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()); + }); + }; + __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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return (g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g); + function verb(n) { + return function (v) { + return step([n, v]); + }; } - } - } - }; - 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 step(op) { + if (f) throw new TypeError("Generator is already executing."); + while ((g && (g = 0, op[0] && (_ = 0)), _)) try { + if ((f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)) return t; + if ((y = 0, t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { + value: op[1], + done: false + }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; } }; - } - } - function 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 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); + __exportStar = function (m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + __createBinding = Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || (("get" in desc) ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; + } + Object.defineProperty(o, k2, desc); + } : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + __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 + }; } - 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; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + __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; + } } - } 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; + return ar; + }; + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; + }; + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; (j++, k++)) r[k] = a[j]; + return r; + }; + __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]; + } } - } 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; + return to.concat(ar || Array.prototype.slice.call(from)); + }; + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return (i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; } - } - 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; + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); } } - 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; + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); } } - 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; - } - } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - } - 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; + function fulfill(value) { + resume("next", value); } - } - 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; + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } + }; + __asyncDelegator = function (o) { + var i, p; + return (i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i); + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: false + } : f ? f(v) : v; + } : f; + } + }; + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && (function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v), settle(resolve, reject, v.done, v.value)); + }); + }); + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + }; + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + return cooked; + }; + var __setModuleDefault = Object.create ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v }); - } - 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); - } + } : function (o, v) { + o["default"] = v; + }; + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + __importDefault = function (mod) { + return mod && mod.__esModule ? mod : { + "default": mod + }; + }; + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value); + }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function () { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ + value: value, + dispose: dispose, + async: async + }); + } else if (async) { + env.stack.push({ + async: true + }); } - }); - } - 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); + return value; + }; + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return (e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e); + }; + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; } - }); - }; + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return (s = 0, env.stack.push(r), Promise.resolve().then(next)); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return (s |= 2, Promise.resolve(result).then(next, function (e) { + fail(e); + return next(); + })); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); + }); + })(tslib$1); + var tslibExports = tslib$1.exports; + + 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 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 defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } - 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 `; + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; } - 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."); - } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; } - 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 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 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."); - } + 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); + } + } + + + } - 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; + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - 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; + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); } else { - out[p++] = c >> 18 | 240; - out[p++] = c >> 12 & 63 | 128; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; + queueIndex = -1; } - } - 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; + if (queue.length) { + drainQueue(); } - } - 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 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 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 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); + } } - function getModularInstance(service) { - if (service && service._delegate) { - return service._delegate; - } else { - return service; - } + // 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 = {}; - var index_esm2017$2 = /*#__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, - 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 - }); + function noop$1() {} - /** - * 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; - } + 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'); } - /** - * @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]'; + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } - /** - * @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 mulitple 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/can not 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 */; - } + // 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() }; - /** - * @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()); - } + // 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 index_esm2017$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - Component: Component, - ComponentContainer: ComponentContainer, - Provider: Provider - }); + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } - var index_cjs = {}; - - var tslib = {exports: {}}; + 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 + }; - (function (module) { - var __extends; - var __assign; - var __rest; - var __decorate; - var __param; - var __esDecorate; - var __runInitializers; - var __propKey; - var __setFunctionName; - var __metadata; - var __awaiter; - var __generator; - var __exportStar; - var __values; - var __read; - var __spread; - var __spreadArrays; - var __spreadArray; - var __await; - var __asyncGenerator; - var __asyncDelegator; - var __asyncValues; - var __makeTemplateObject; - var __importStar; - var __importDefault; - var __classPrivateFieldGet; - var __classPrivateFieldSet; - var __classPrivateFieldIn; - var __createBinding; - var __addDisposableResource; - var __disposeResources; - (function (factory) { - var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {}; - { - factory(createExporter(root, createExporter(module.exports))); + 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; } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { - value: true - }); - } else { - exports.__esModule = true; + } + 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; } } - return function (id, v) { - return exports[id] = previous ? previous(id, v) : v; - }; + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); } - })(function (exporter) { - var 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]; - }); - __extends = 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; + 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(); } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - __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]; + 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 t; - }); - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + 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; + } } - return t; - }; - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return (c > 3 && r && Object.defineProperty(target, key, r), r); - }; - __param = function (paramIndex, decorator) { - return function (target, key) { - decorator(target, key, paramIndex); - }; - }; - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { - get: descriptor.get, - set: descriptor.set - } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + } + }; + 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 = {}; } - return useValue ? value : void 0; - }; - __propKey = function (x) { - return typeof x === "symbol" ? x : ("").concat(x); - }; - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? ("[").concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { - configurable: true, - value: prefix ? ("").concat(prefix, " ", name) : name - }); - }; - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); + 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); } - 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); + if (typeof callback === "function") { + this.promise.catch(() => {}); + if (callback.length === 1) { + callback(error); + } else { + callback(error, value); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - __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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return (g.next = verb(0), g["throw"] = verb(1), g["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 ((g && (g = 0, op[0] && (_ = 0)), _)) 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 - }; - } - }; - __exportStar = function (m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - __createBinding = Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || (("get" in desc) ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); - } : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; }; - __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 - }; + } + } + 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 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); }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - __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; - }; - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); - return ar; - }; - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; (j++, k++)) r[k] = a[j]; - return r; - }; - __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)); - }; - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return (i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function awaitReturn(f) { - return function (v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); - } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); + 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; } - function reject(value) { - resume("throw", value); + } 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; } - function settle(f, v) { - if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } 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; } - }; - __asyncDelegator = function (o) { - var i, p; - return (i = {}, verb("next"), verb("throw", function (e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function () { - return this; - }, i); - function verb(n, f) { - i[n] = o[n] ? function (v) { - return (p = !p) ? { - value: __await(o[n](v)), - done: false - } : f ? f(v) : v; - } : f; - } - }; - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && (function (v) { - return new Promise(function (resolve, reject) { - (v = o[n](v), settle(resolve, reject, v.done, v.value)); - }); - }); - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } - }; - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { - value: raw - }); - } else { - cooked.raw = raw; - } - return cooked; - }; - var __setModuleDefault = Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); - } : function (o, v) { - o["default"] = v; - }; - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - __importDefault = function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; - }; - __classPrivateFieldGet = function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value); - }; - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - __addDisposableResource = function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; + } + 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; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + } else { + if (i < 60) { + f = b & c | d & (b | c); + k = 2400959708; + } else { + f = b ^ c ^ d; + k = 3395469782; } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function () { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); - } - }; - env.stack.push({ - value: value, - dispose: dispose, - async: async - }); - } else if (async) { - env.stack.push({ - async: true - }); } - return value; - }; - var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return (e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e); - }; - __disposeResources = function (env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; + 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; + } } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return (s = 0, env.stack.push(r), Promise.resolve().then(next)); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return (s |= 2, Promise.resolve(result).then(next, function (e) { - fail(e); - return next(); - })); - } else s |= 1; - } catch (e) { - fail(e); + 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; } } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; } - return next(); - }; - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); - exporter("__addDisposableResource", __addDisposableResource); - exporter("__disposeResources", __disposeResources); - }); - })(tslib); - var tslibExports = tslib.exports; + } + 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, + 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$1 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); + + Object.defineProperty(index_cjs$1, '__esModule', { value: true }); + + var tslib = tslibExports; + var util = require$$4$1; + + /** + * Component for service name T, e.g. `auth`, `auth-internal` + */ + var Component = /** @class */ (function () { + /** + * + * @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 + */ + function Component(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; + } + Component.prototype.setInstantiationMode = function (mode) { + this.instantiationMode = mode; + return this; + }; + Component.prototype.setMultipleInstances = function (multipleInstances) { + this.multipleInstances = multipleInstances; + return this; + }; + Component.prototype.setServiceProps = function (props) { + this.serviceProps = props; + return this; + }; + Component.prototype.setInstanceCreatedCallback = function (callback) { + this.onInstanceCreated = callback; + return this; + }; + return Component; + }()); + + /** + * @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. + */ + var 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 + */ + var Provider = /** @class */ (function () { + function Provider(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 mulitple instances of a service + * if this.component.multipleInstances is true. + */ + Provider.prototype.get = function (identifier) { + // if multipleInstances is not supported, use the default name + var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + if (!this.instancesDeferred.has(normalizedIdentifier)) { + var 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 { + var 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; + }; + Provider.prototype.getImmediate = function (options) { + var _a; + // if multipleInstances is not supported, use the default name + var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); + var 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/can not be auto-initialized at the moment, return null if the optional flag is set, or throw + if (optional) { + return null; + } + else { + throw Error("Service ".concat(this.name, " is not available")); + } + } + }; + Provider.prototype.getComponent = function () { + return this.component; + }; + Provider.prototype.setComponent = function (component) { + var e_1, _a; + if (component.name !== this.name) { + throw Error("Mismatching Component ".concat(component.name, " for Provider ").concat(this.name, ".")); + } + if (this.component) { + throw Error("Component for ".concat(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? + } + } + try { + // 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 (var _b = tslib.__values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) { + var _d = tslib.__read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1]; + var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + try { + // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. + var 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. + } + } + } + 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; } + } + }; + Provider.prototype.clearInstance = function (identifier) { + if (identifier === void 0) { 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? + Provider.prototype.delete = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var services; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + services = Array.from(this.instances.values()); + return [4 /*yield*/, Promise.all(tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(services + .filter(function (service) { return 'INTERNAL' in service; }) // legacy services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(function (service) { return service.INTERNAL.delete(); })), false), tslib.__read(services + .filter(function (service) { return '_delete' in service; }) // modularized services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(function (service) { return service._delete(); })), false))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + Provider.prototype.isComponentSet = function () { + return this.component != null; + }; + Provider.prototype.isInitialized = function (identifier) { + if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } + return this.instances.has(identifier); + }; + Provider.prototype.getOptions = function (identifier) { + if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } + return this.instancesOptions.get(identifier) || {}; + }; + Provider.prototype.initialize = function (opts) { + var e_2, _a; + if (opts === void 0) { opts = {}; } + var _b = opts.options, options = _b === void 0 ? {} : _b; + var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); + if (this.isInitialized(normalizedIdentifier)) { + throw Error("".concat(this.name, "(").concat(normalizedIdentifier, ") has already been initialized")); + } + if (!this.isComponentSet()) { + throw Error("Component ".concat(this.name, " has not been registered yet")); + } + var instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier, + options: options + }); + try { + // resolve any pending promise waiting for the service instance + for (var _c = tslib.__values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) { + var _e = tslib.__read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1]; + var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + if (normalizedIdentifier === normalizedDeferredIdentifier) { + instanceDeferred.resolve(instance); + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + 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 + */ + Provider.prototype.onInit = function (callback, identifier) { + var _a; + var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); + existingCallbacks.add(callback); + this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); + var existingInstance = this.instances.get(normalizedIdentifier); + if (existingInstance) { + callback(existingInstance, normalizedIdentifier); + } + return function () { + existingCallbacks.delete(callback); + }; + }; + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) { + var e_3, _a; + var callbacks = this.onInitCallbacks.get(identifier); + if (!callbacks) { + return; + } + try { + for (var callbacks_1 = tslib.__values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { + var callback = callbacks_1_1.value; + try { + callback(instance, identifier); + } + catch (_b) { + // ignore errors in the onInit callback + } + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); + } + finally { if (e_3) throw e_3.error; } + } + }; + Provider.prototype.getOrInitializeService = function (_a) { + var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b; + var instance = this.instances.get(instanceIdentifier); + if (!instance && this.component) { + instance = this.component.instanceFactory(this.container, { + instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), + options: 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 (_c) { + // ignore errors in the onInstanceCreatedCallback + } + } + } + return instance || null; + }; + Provider.prototype.normalizeInstanceIdentifier = function (identifier) { + if (identifier === void 0) { 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. + } + }; + Provider.prototype.shouldAutoInitialize = function () { + return (!!this.component && + this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */); + }; + return Provider; + }()); + // 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` + */ + var ComponentContainer = /** @class */ (function () { + function ComponentContainer(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 + */ + ComponentContainer.prototype.addComponent = function (component) { + var provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + throw new Error("Component ".concat(component.name, " has already been registered with ").concat(this.name)); + } + provider.setComponent(component); + }; + ComponentContainer.prototype.addOrOverwriteComponent = function (component) { + var 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. + */ + ComponentContainer.prototype.getProvider = function (name) { + if (this.providers.has(name)) { + return this.providers.get(name); + } + // create a Provider for a service that hasn't registered with Firebase + var provider = new Provider(name, this); + this.providers.set(name, provider); + return provider; + }; + ComponentContainer.prototype.getProviders = function () { + return Array.from(this.providers.values()); + }; + return ComponentContainer; + }()); + + index_cjs$1.Component = Component; + index_cjs$1.ComponentContainer = ComponentContainer; + index_cjs$1.Provider = Provider; + + var index_cjs = {}; (function (exports) { @@ -2610,10 +2668,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } (index_cjs)); - var build = {}; - - var wrapIdbValue$1 = {}; - const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); let idbProxyableTypes; @@ -2798,16 +2852,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } const unwrap = (value) => reverseTransformCache.get(value); - wrapIdbValue$1.instanceOfAny = instanceOfAny; - wrapIdbValue$1.replaceTraps = replaceTraps; - wrapIdbValue$1.reverseTransformCache = reverseTransformCache; - wrapIdbValue$1.unwrap = unwrap; - wrapIdbValue$1.wrap = wrap; - - Object.defineProperty(build, '__esModule', { value: true }); - - var wrapIdbValue = wrapIdbValue$1; - /** * Open a database. * @@ -2817,10 +2861,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { const request = indexedDB.open(name, version); - const openPromise = wrapIdbValue.wrap(request); + const openPromise = wrap(request); if (upgrade) { request.addEventListener('upgradeneeded', (event) => { - upgrade(wrapIdbValue.wrap(request.result), event.oldVersion, event.newVersion, wrapIdbValue.wrap(request.transaction), event); + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); }); } if (blocked) { @@ -2851,7 +2895,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 event.oldVersion, event)); } - return wrapIdbValue.wrap(request).then(() => undefined); + return wrap(request).then(() => undefined); } const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; @@ -2893,1197 +2937,1415 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; cachedMethods.set(prop, method); return method; } - wrapIdbValue.replaceTraps((oldTraps) => ({ + 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), })); - build.unwrap = wrapIdbValue.unwrap; - build.wrap = wrapIdbValue.wrap; - build.deleteDB = deleteDB; - var openDB_1 = build.openDB = openDB; - - /** - * @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$p = "@firebase/app"; - const version$1 = "0.10.10"; - - /** - * @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$o = "@firebase/app-compat"; - - const name$n = "@firebase/analytics-compat"; - - const name$m = "@firebase/analytics"; - - const name$l = "@firebase/app-check-compat"; - - const name$k = "@firebase/app-check"; - - const name$j = "@firebase/auth"; - - const name$i = "@firebase/auth-compat"; - - const name$h = "@firebase/database"; - - 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"; + var build = /*#__PURE__*/Object.freeze({ + __proto__: null, + deleteDB: deleteDB, + openDB: openDB, + unwrap: unwrap, + wrap: wrap + }); - const name$4 = "@firebase/storage-compat"; + var require$$4 = /*@__PURE__*/getAugmentedNamespace(build); - const name$3 = "@firebase/firestore"; + (function (exports) { - const name$2 = "@firebase/vertexai-preview"; + Object.defineProperty(exports, '__esModule', { value: true }); - const name$1 = "@firebase/firestore-compat"; + var component = index_cjs$1; + var tslib = tslibExports; + var logger$1 = index_cjs; + var util = require$$4$1; + var idb = require$$4; - const name = "firebase"; - const version = "10.13.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. + */ + var PlatformLoggerServiceImpl = /** @class */ (function () { + function PlatformLoggerServiceImpl(container) { + this.container = container; + } + // In initial implementation, this will be called by installations on + // auth token refresh, and installations will send this string. + PlatformLoggerServiceImpl.prototype.getPlatformInfoString = function () { + var providers = this.container.getProviders(); + // Loop through providers and get library/version pairs from any that are + // version components. + return providers + .map(function (provider) { + if (isVersionServiceProvider(provider)) { + var service = provider.getImmediate(); + return "".concat(service.library, "/").concat(service.version); + } + else { + return null; + } + }) + .filter(function (logString) { return logString; }) + .join(' '); + }; + return PlatformLoggerServiceImpl; + }()); + /** + * + * @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) { + var component = provider.getComponent(); + return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */; + } - /** - * @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$p]: 'fire-core', - [name$o]: 'fire-core-compat', - [name$m]: 'fire-analytics', - [name$n]: 'fire-analytics-compat', - [name$k]: 'fire-app-check', - [name$l]: 'fire-app-check-compat', - [name$j]: 'fire-auth', - [name$i]: 'fire-auth-compat', - [name$h]: 'fire-rtdb', - [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' - }; + var name$p = "@firebase/app"; + var version$1 = "0.10.10"; - /** - * @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. + */ + var logger = new logger$1.Logger('@firebase/app'); - /** - * @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); + var name$o = "@firebase/app-compat"; - /** - * @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 }); - } - } - } + var name$n = "@firebase/analytics-compat"; - /** - * @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$p, 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 */); - } - } - } + var name$m = "@firebase/analytics"; + + var name$l = "@firebase/app-check-compat"; + + var name$k = "@firebase/app-check"; + + var name$j = "@firebase/auth"; + + var name$i = "@firebase/auth-compat"; + + var name$h = "@firebase/database"; + + var name$g = "@firebase/database-compat"; + + var name$f = "@firebase/functions"; + + var name$e = "@firebase/functions-compat"; + + var name$d = "@firebase/installations"; + + var name$c = "@firebase/installations-compat"; + + var name$b = "@firebase/messaging"; + + var name$a = "@firebase/messaging-compat"; + + var name$9 = "@firebase/performance"; + + var name$8 = "@firebase/performance-compat"; + + var name$7 = "@firebase/remote-config"; + + var name$6 = "@firebase/remote-config-compat"; + + var name$5 = "@firebase/storage"; + + var name$4 = "@firebase/storage-compat"; + + var name$3 = "@firebase/firestore"; + + var name$2 = "@firebase/vertexai-preview"; + + var name$1 = "@firebase/firestore-compat"; + + var name = "firebase"; + var version = "10.13.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. + */ + var _a$1; + /** + * The default app name + * + * @internal + */ + var DEFAULT_ENTRY_NAME = '[DEFAULT]'; + var PLATFORM_LOG_STRING = (_a$1 = {}, + _a$1[name$p] = 'fire-core', + _a$1[name$o] = 'fire-core-compat', + _a$1[name$m] = 'fire-analytics', + _a$1[name$n] = 'fire-analytics-compat', + _a$1[name$k] = 'fire-app-check', + _a$1[name$l] = 'fire-app-check-compat', + _a$1[name$j] = 'fire-auth', + _a$1[name$i] = 'fire-auth-compat', + _a$1[name$h] = 'fire-rtdb', + _a$1[name$g] = 'fire-rtdb-compat', + _a$1[name$f] = 'fire-fn', + _a$1[name$e] = 'fire-fn-compat', + _a$1[name$d] = 'fire-iid', + _a$1[name$c] = 'fire-iid-compat', + _a$1[name$b] = 'fire-fcm', + _a$1[name$a] = 'fire-fcm-compat', + _a$1[name$9] = 'fire-perf', + _a$1[name$8] = 'fire-perf-compat', + _a$1[name$7] = 'fire-rc', + _a$1[name$6] = 'fire-rc-compat', + _a$1[name$5] = 'fire-gcs', + _a$1[name$4] = 'fire-gcs-compat', + _a$1[name$3] = 'fire-fst', + _a$1[name$1] = 'fire-fst-compat', + _a$1[name$2] = 'fire-vertex', + _a$1['fire-js'] = 'fire-js', + _a$1[name] = 'fire-js-all', + _a$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. + */ + /** + * @internal + */ + var _apps = new Map(); + /** + * @internal + */ + var _serverApps = new Map(); + /** + * Registered components. + * + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var _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 ".concat(component.name, " failed to register with FirebaseApp ").concat(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) { + var e_1, _a, e_2, _b; + var componentName = component.name; + if (_components.has(componentName)) { + logger.debug("There were multiple attempts to register component ".concat(componentName, ".")); + return false; + } + _components.set(componentName, component); + try { + // add the component to existing app instances + for (var _c = tslib.__values(_apps.values()), _d = _c.next(); !_d.done; _d = _c.next()) { + var app = _d.value; + _addComponent(app, component); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (var _e = tslib.__values(_serverApps.values()), _f = _e.next(); !_f.done; _f = _e.next()) { + var serverApp = _f.value; + _addComponent(serverApp, component); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_f && !_f.done && (_b = _e.return)) _b.call(_e); + } + finally { if (e_2) throw e_2.error; } + } + 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) { + var 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) { + if (instanceIdentifier === void 0) { 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. + */ + var _a; + var ERRORS = (_a = {}, + _a["no-app" /* AppError.NO_APP */] = "No Firebase App '{$appName}' has been created - " + + 'call initializeApp() first', + _a["bad-app-name" /* AppError.BAD_APP_NAME */] = "Illegal App name: '{$appName}'", + _a["duplicate-app" /* AppError.DUPLICATE_APP */] = "Firebase App named '{$appName}' already exists with different options or config", + _a["app-deleted" /* AppError.APP_DELETED */] = "Firebase App named '{$appName}' already deleted", + _a["server-app-deleted" /* AppError.SERVER_APP_DELETED */] = 'Firebase Server App has been deleted', + _a["no-options" /* AppError.NO_OPTIONS */] = 'Need to provide options, when not being deployed to hosting via source.', + _a["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */] = 'firebase.{$appName}() takes either no argument or a ' + + 'Firebase App instance.', + _a["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */] = 'First argument to `onLog` must be null or a function.', + _a["idb-open" /* AppError.IDB_OPEN */] = 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.', + _a["idb-get" /* AppError.IDB_GET */] = 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.', + _a["idb-set" /* AppError.IDB_WRITE */] = 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.', + _a["idb-delete" /* AppError.IDB_DELETE */] = 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.', + _a["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */] = 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.', + _a["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */] = 'FirebaseServerApp is not for use in browser environments.', + _a); + var 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. + */ + var FirebaseAppImpl = /** @class */ (function () { + function FirebaseAppImpl(options, config, container) { + var _this = this; + this._isDeleted = false; + this._options = tslib.__assign({}, options); + this._config = tslib.__assign({}, config); + this._name = config.name; + this._automaticDataCollectionEnabled = + config.automaticDataCollectionEnabled; + this._container = container; + this.container.addComponent(new component.Component('app', function () { return _this; }, "PUBLIC" /* ComponentType.PUBLIC */)); + } + Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", { + get: function () { + this.checkDestroyed(); + return this._automaticDataCollectionEnabled; + }, + set: function (val) { + this.checkDestroyed(); + this._automaticDataCollectionEnabled = val; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "name", { + get: function () { + this.checkDestroyed(); + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "options", { + get: function () { + this.checkDestroyed(); + return this._options; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "config", { + get: function () { + this.checkDestroyed(); + return this._config; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "container", { + get: function () { + return this._container; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "isDeleted", { + get: function () { + return this._isDeleted; + }, + set: function (val) { + this._isDeleted = val; + }, + enumerable: false, + configurable: true + }); + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + FirebaseAppImpl.prototype.checkDestroyed = function () { + if (this.isDeleted) { + throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name }); + } + }; + return FirebaseAppImpl; + }()); - /** - * @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 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. + */ + var FirebaseServerAppImpl = /** @class */ (function (_super) { + tslib.__extends(FirebaseServerAppImpl, _super); + function FirebaseServerAppImpl(options, serverConfig, name, container) { + var _this = this; + // Build configuration parameters for the FirebaseAppImpl base class. + var automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined + ? serverConfig.automaticDataCollectionEnabled + : false; + // Create the FirebaseAppSettings object for the FirebaseAppImp constructor. + var config = { + name: name, + automaticDataCollectionEnabled: automaticDataCollectionEnabled + }; + if (options.apiKey !== undefined) { + // Construct the parent FirebaseAppImp object. + _this = _super.call(this, options, config, container) || this; + } + else { + var appImpl = options; + _this = _super.call(this, appImpl.options, config, container) || this; + } + // Now construct the data for the FirebaseServerAppImpl. + _this._serverConfig = tslib.__assign({ automaticDataCollectionEnabled: automaticDataCollectionEnabled }, serverConfig); + _this._finalizationRegistry = null; + if (typeof FinalizationRegistry !== 'undefined') { + _this._finalizationRegistry = new FinalizationRegistry(function () { + _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$p, version$1, 'serverapp'); + return _this; + } + FirebaseServerAppImpl.prototype.toJSON = function () { + return undefined; + }; + Object.defineProperty(FirebaseServerAppImpl.prototype, "refCount", { + get: function () { + return this._refCount; + }, + enumerable: false, + configurable: true + }); + // Increment the reference count of this server app. If an object is provided, register it + // with the finalization registry. + FirebaseServerAppImpl.prototype.incRefCount = function (obj) { + if (this.isDeleted) { + return; + } + this._refCount++; + if (obj !== undefined && this._finalizationRegistry !== null) { + this._finalizationRegistry.register(obj, this); + } + }; + // Decrement the reference count. + FirebaseServerAppImpl.prototype.decRefCount = function () { + 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(...). + FirebaseServerAppImpl.prototype.automaticCleanup = function () { + void deleteApp(this); + }; + Object.defineProperty(FirebaseServerAppImpl.prototype, "settings", { + get: function () { + this.checkDestroyed(); + return this._serverConfig; + }, + enumerable: false, + configurable: true + }); + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + FirebaseServerAppImpl.prototype.checkDestroyed = function () { + if (this.isDeleted) { + throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */); + } + }; + return FirebaseServerAppImpl; + }(FirebaseAppImpl)); - /** - * @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_1(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 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 + */ + var SDK_VERSION = version; + function initializeApp(_options, rawConfig) { + var e_1, _a; + if (rawConfig === void 0) { rawConfig = {}; } + var options = _options; + if (typeof rawConfig !== 'object') { + var name_1 = rawConfig; + rawConfig = { name: name_1 }; + } + var config = tslib.__assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig); + var 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 */); + } + var 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 }); + } + } + var container = new component.ComponentContainer(name); + try { + for (var _b = tslib.__values(_components.values()), _c = _b.next(); !_c.done; _c = _b.next()) { + var component$1 = _c.value; + container.addComponent(component$1); + } + } + 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; } + } + var newApp = new FirebaseAppImpl(options, config, container); + _apps.set(name, newApp); + return newApp; + } + function initializeServerApp(_options, _serverAppConfig) { + var e_2, _a; + 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; + } + var appOptions; + if (_isFirebaseApp(_options)) { + appOptions = _options.options; + } + else { + appOptions = _options; + } + // Build an app name based on a hash of the configuration options. + var nameObj = tslib.__assign(tslib.__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; + } + var hashCode = function (s) { + return tslib.__spreadArray([], tslib.__read(s), false).reduce(function (hash, c) { return (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 */, {}); + } + } + var nameString = '' + hashCode(JSON.stringify(nameObj)); + var existingApp = _serverApps.get(nameString); + if (existingApp) { + existingApp.incRefCount(_serverAppConfig.releaseOnDeref); + return existingApp; + } + var container = new component.ComponentContainer(nameString); + try { + for (var _b = tslib.__values(_components.values()), _c = _b.next(); !_c.done; _c = _b.next()) { + var component$1 = _c.value; + container.addComponent(component$1); + } + } + 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; } + } + var 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) { + if (name === void 0) { name = DEFAULT_ENTRY_NAME; } + var 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 + */ + function deleteApp(app) { + return tslib.__awaiter(this, void 0, void 0, function () { + var cleanupProviders, name, firebaseServerApp; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + cleanupProviders = false; + name = app.name; + if (_apps.has(name)) { + cleanupProviders = true; + _apps.delete(name); + } + else if (_serverApps.has(name)) { + firebaseServerApp = app; + if (firebaseServerApp.decRefCount() <= 0) { + _serverApps.delete(name); + cleanupProviders = true; + } + } + if (!cleanupProviders) return [3 /*break*/, 2]; + return [4 /*yield*/, Promise.all(app.container + .getProviders() + .map(function (provider) { return provider.delete(); }))]; + case 1: + _a.sent(); + app.isDeleted = true; + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + } + /** + * 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. + var library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName; + if (variant) { + library += "-".concat(variant); + } + var libraryMismatch = library.match(/\s|\//); + var versionMismatch = version.match(/\s|\//); + if (libraryMismatch || versionMismatch) { + var warning = [ + "Unable to register library \"".concat(library, "\" with version \"").concat(version, "\":") + ]; + if (libraryMismatch) { + warning.push("library name \"".concat(library, "\" contains illegal characters (whitespace or \"/\")")); + } + if (libraryMismatch && versionMismatch) { + warning.push('and'); + } + if (versionMismatch) { + warning.push("version name \"".concat(version, "\" contains illegal characters (whitespace or \"/\")")); + } + logger.warn(warning.join(' ')); + return; + } + _registerComponent(new component.Component("".concat(library, "-version"), function () { return ({ library: library, version: 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 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 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. + */ + var DB_NAME = 'firebase-heartbeat-database'; + var DB_VERSION = 1; + var STORE_NAME = 'firebase-heartbeat-store'; + var dbPromise = null; + function getDbPromise() { + if (!dbPromise) { + dbPromise = idb.openDB(DB_NAME, DB_VERSION, { + upgrade: function (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(function (e) { + throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, { + originalErrorMessage: e.message + }); + }); + } + return dbPromise; + } + function readHeartbeatsFromIndexedDB(app) { + return tslib.__awaiter(this, void 0, void 0, function () { + var db, tx, result, e_1, idbGetError; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 4, , 5]); + return [4 /*yield*/, getDbPromise()]; + case 1: + db = _a.sent(); + tx = db.transaction(STORE_NAME); + return [4 /*yield*/, tx.objectStore(STORE_NAME).get(computeKey(app))]; + case 2: + result = _a.sent(); + // We already have the value but tx.done can throw, + // so we need to await it here to catch errors + return [4 /*yield*/, tx.done]; + case 3: + // We already have the value but tx.done can throw, + // so we need to await it here to catch errors + _a.sent(); + return [2 /*return*/, result]; + case 4: + e_1 = _a.sent(); + if (e_1 instanceof util.FirebaseError) { + logger.warn(e_1.message); + } + else { + idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, { + originalErrorMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message + }); + logger.warn(idbGetError.message); + } + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); + } + function writeHeartbeatsToIndexedDB(app, heartbeatObject) { + return tslib.__awaiter(this, void 0, void 0, function () { + var db, tx, objectStore, e_2, idbGetError; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 4, , 5]); + return [4 /*yield*/, getDbPromise()]; + case 1: + db = _a.sent(); + tx = db.transaction(STORE_NAME, 'readwrite'); + objectStore = tx.objectStore(STORE_NAME); + return [4 /*yield*/, objectStore.put(heartbeatObject, computeKey(app))]; + case 2: + _a.sent(); + return [4 /*yield*/, tx.done]; + case 3: + _a.sent(); + return [3 /*break*/, 5]; + case 4: + e_2 = _a.sent(); + if (e_2 instanceof util.FirebaseError) { + logger.warn(e_2.message); + } + else { + idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, { + originalErrorMessage: e_2 === null || e_2 === void 0 ? void 0 : e_2.message + }); + logger.warn(idbGetError.message); + } + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); + } + function computeKey(app) { + return "".concat(app.name, "!").concat(app.options.appId); + } - /** - * @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$p, version$1, variant); - // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation - registerVersion(name$p, version$1, 'esm2017'); - // Register platform SDK identifier (no version). - registerVersion('fire-js', ''); - } + /** + * @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. + */ + var MAX_HEADER_BYTES = 1024; + // 30 days + var STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000; + var HeartbeatServiceImpl = /** @class */ (function () { + function HeartbeatServiceImpl(container) { + var _this = this; + 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; + var app = this.container.getProvider('app').getImmediate(); + this._storage = new HeartbeatStorageImpl(app); + this._heartbeatsCachePromise = this._storage.read().then(function (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. + */ + HeartbeatServiceImpl.prototype.triggerHeartbeat = function () { + var _a, _b; + return tslib.__awaiter(this, void 0, void 0, function () { + var platformLogger, agent, date_1, _c, e_1; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 3, , 4]); + platformLogger = this.container + .getProvider('platform-logger') + .getImmediate(); + agent = platformLogger.getPlatformInfoString(); + date_1 = getUTCDateString(); + if (!(((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null)) return [3 /*break*/, 2]; + _c = this; + return [4 /*yield*/, this._heartbeatsCachePromise]; + case 1: + _c._heartbeatsCache = _d.sent(); + // 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 [2 /*return*/]; + } + _d.label = 2; + case 2: + // 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_1 || + this._heartbeatsCache.heartbeats.some(function (singleDateHeartbeat) { return singleDateHeartbeat.date === date_1; })) { + return [2 /*return*/]; + } + else { + // There is no entry for this date. Create one. + this._heartbeatsCache.heartbeats.push({ date: date_1, agent: agent }); + } + // Remove entries older than 30 days. + this._heartbeatsCache.heartbeats = + this._heartbeatsCache.heartbeats.filter(function (singleDateHeartbeat) { + var hbTimestamp = new Date(singleDateHeartbeat.date).valueOf(); + var now = Date.now(); + return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS; + }); + return [2 /*return*/, this._storage.overwrite(this._heartbeatsCache)]; + case 3: + e_1 = _d.sent(); + logger.warn(e_1); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + /** + * 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. + */ + HeartbeatServiceImpl.prototype.getHeartbeatsHeader = function () { + var _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var date, _b, heartbeatsToSend, unsentEntries, headerString, e_2; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, 6, , 7]); + if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2]; + return [4 /*yield*/, this._heartbeatsCachePromise]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + // 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 [2 /*return*/, '']; + } + date = getUTCDateString(); + _b = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats), heartbeatsToSend = _b.heartbeatsToSend, unsentEntries = _b.unsentEntries; + 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)) return [3 /*break*/, 4]; + // 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. + return [4 /*yield*/, this._storage.overwrite(this._heartbeatsCache)]; + case 3: + // 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. + _c.sent(); + return [3 /*break*/, 5]; + case 4: + this._heartbeatsCache.heartbeats = []; + // Do not wait for this, to reduce latency. + void this._storage.overwrite(this._heartbeatsCache); + _c.label = 5; + case 5: return [2 /*return*/, headerString]; + case 6: + e_2 = _c.sent(); + logger.warn(e_2); + return [2 /*return*/, '']; + case 7: return [2 /*return*/]; + } + }); + }); + }; + return HeartbeatServiceImpl; + }()); + function getUTCDateString() { + var today = new Date(); + // Returns date format 'YYYY-MM-DD' + return today.toISOString().substring(0, 10); + } + function extractHeartbeatsForHeader(heartbeatsCache, maxSize) { + var e_3, _a; + if (maxSize === void 0) { maxSize = MAX_HEADER_BYTES; } + // Heartbeats grouped by user agent in the standard format to be sent in + // the header. + var heartbeatsToSend = []; + // Single date format heartbeats that are not sent. + var unsentEntries = heartbeatsCache.slice(); + var _loop_1 = function (singleDateHeartbeat) { + // Look for an existing entry with the same user agent. + var heartbeatEntry = heartbeatsToSend.find(function (hb) { return 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(); + return "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(); + return "break"; + } + } + // Pop unsent entry from queue. (Skipped if adding the entry exceeded + // quota and the loop breaks early.) + unsentEntries = unsentEntries.slice(1); + }; + try { + for (var heartbeatsCache_1 = tslib.__values(heartbeatsCache), heartbeatsCache_1_1 = heartbeatsCache_1.next(); !heartbeatsCache_1_1.done; heartbeatsCache_1_1 = heartbeatsCache_1.next()) { + var singleDateHeartbeat = heartbeatsCache_1_1.value; + var state_1 = _loop_1(singleDateHeartbeat); + if (state_1 === "break") + break; + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (heartbeatsCache_1_1 && !heartbeatsCache_1_1.done && (_a = heartbeatsCache_1.return)) _a.call(heartbeatsCache_1); + } + finally { if (e_3) throw e_3.error; } + } + return { + heartbeatsToSend: heartbeatsToSend, + unsentEntries: unsentEntries + }; + } + var HeartbeatStorageImpl = /** @class */ (function () { + function HeartbeatStorageImpl(app) { + this.app = app; + this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck(); + } + HeartbeatStorageImpl.prototype.runIndexedDBEnvironmentCheck = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + if (!util.isIndexedDBAvailable()) { + return [2 /*return*/, false]; + } + else { + return [2 /*return*/, util.validateIndexedDBOpenable() + .then(function () { return true; }) + .catch(function () { return false; })]; + } + }); + }); + }; + /** + * Read all heartbeats. + */ + HeartbeatStorageImpl.prototype.read = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var canUseIndexedDB, idbHeartbeatObject; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this._canUseIndexedDBPromise]; + case 1: + canUseIndexedDB = _a.sent(); + if (!!canUseIndexedDB) return [3 /*break*/, 2]; + return [2 /*return*/, { heartbeats: [] }]; + case 2: return [4 /*yield*/, readHeartbeatsFromIndexedDB(this.app)]; + case 3: + idbHeartbeatObject = _a.sent(); + if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) { + return [2 /*return*/, idbHeartbeatObject]; + } + else { + return [2 /*return*/, { heartbeats: [] }]; + } + case 4: return [2 /*return*/]; + } + }); + }); + }; + // overwrite the storage with the provided heartbeats + HeartbeatStorageImpl.prototype.overwrite = function (heartbeatsObject) { + var _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var canUseIndexedDB, existingHeartbeatsObject; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this._canUseIndexedDBPromise]; + case 1: + canUseIndexedDB = _b.sent(); + if (!!canUseIndexedDB) return [3 /*break*/, 2]; + return [2 /*return*/]; + case 2: return [4 /*yield*/, this.read()]; + case 3: + existingHeartbeatsObject = _b.sent(); + return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: heartbeatsObject.heartbeats + })]; + } + }); + }); + }; + // add heartbeats + HeartbeatStorageImpl.prototype.add = function (heartbeatsObject) { + var _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var canUseIndexedDB, existingHeartbeatsObject; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this._canUseIndexedDBPromise]; + case 1: + canUseIndexedDB = _b.sent(); + if (!!canUseIndexedDB) return [3 /*break*/, 2]; + return [2 /*return*/]; + case 2: return [4 /*yield*/, this.read()]; + case 3: + existingHeartbeatsObject = _b.sent(); + return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(existingHeartbeatsObject.heartbeats), false), tslib.__read(heartbeatsObject.heartbeats), false) + })]; + } + }); + }); + }; + return HeartbeatStorageImpl; + }()); + /** + * 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; + } - /** - * Firebase App - * - * @remarks This package coordinates the communication between the different Firebase components - * @packageDocumentation - */ - registerCoreComponents(''); + /** + * @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', function (container) { return new PlatformLoggerServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */)); + _registerComponent(new component.Component('heartbeat', function (container) { return new HeartbeatServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */)); + // Register `app` package. + registerVersion(name$p, version$1, variant); + // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation + registerVersion(name$p, version$1, 'cjs5'); + // Register platform SDK identifier (no version). + registerVersion('fire-js', ''); + } - var index_esm2017 = /*#__PURE__*/Object.freeze({ - __proto__: null, - FirebaseError: FirebaseError, - SDK_VERSION: SDK_VERSION, - _DEFAULT_ENTRY_NAME: DEFAULT_ENTRY_NAME, - _addComponent: _addComponent, - _addOrOverwriteComponent: _addOrOverwriteComponent, - _apps: _apps, - _clearComponents: _clearComponents, - _components: _components, - _getProvider: _getProvider, - _isFirebaseApp: _isFirebaseApp, - _isFirebaseServerApp: _isFirebaseServerApp, - _registerComponent: _registerComponent, - _removeServiceInstance: _removeServiceInstance, - _serverApps: _serverApps, - deleteApp: deleteApp, - getApp: getApp, - getApps: getApps, - initializeApp: initializeApp, - initializeServerApp: initializeServerApp, - onLog: onLog, - registerVersion: registerVersion, - setLogLevel: setLogLevel - }); + /** + * Firebase App + * + * @remarks This package coordinates the communication between the different Firebase components + * @packageDocumentation + */ + registerCoreComponents('node'); - var require$$0 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); + 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.commonjsGlobal = commonjsGlobal; exports.getAugmentedNamespace = getAugmentedNamespace; exports.global = global$1; - exports.index_cjs = index_cjs; - exports.index_esm2017 = index_esm2017$1; - exports.index_esm2017$1 = index_esm2017$2; + exports.index_cjs = index_cjs$2; + exports.index_cjs$1 = index_cjs; + exports.index_cjs$2 = index_cjs$1; exports.nextTick = nextTick; - exports.require$$0 = require$$0; + exports.require$$4 = require$$4$1; })); 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 0a3eb570d..3514ef9cc 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 @@ -151,207 +151,6 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor return (!isTablet() && !isPhone()) || isWindows8OrAbove(); }; - /** - * @license - * Copyright 2023 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */ - /** - * Map of ARIAMixin properties to attributes - */ - // Shim the global element internals object - // Methods should be fine as noops and properties can generally - // be while on the server. - const ElementInternalsShim = class ElementInternals { - get shadowRoot() { - // Grab the shadow root instance from the Element shim - // to ensure that the shadow root is always available - // to the internals instance even if the mode is 'closed' - return this.__host - .__shadowRoot; - } - constructor(_host) { - this.ariaAtomic = ''; - this.ariaAutoComplete = ''; - this.ariaBrailleLabel = ''; - this.ariaBrailleRoleDescription = ''; - this.ariaBusy = ''; - this.ariaChecked = ''; - this.ariaColCount = ''; - this.ariaColIndex = ''; - this.ariaColSpan = ''; - this.ariaCurrent = ''; - this.ariaDescription = ''; - this.ariaDisabled = ''; - this.ariaExpanded = ''; - this.ariaHasPopup = ''; - this.ariaHidden = ''; - this.ariaInvalid = ''; - this.ariaKeyShortcuts = ''; - this.ariaLabel = ''; - this.ariaLevel = ''; - this.ariaLive = ''; - this.ariaModal = ''; - this.ariaMultiLine = ''; - this.ariaMultiSelectable = ''; - this.ariaOrientation = ''; - this.ariaPlaceholder = ''; - this.ariaPosInSet = ''; - this.ariaPressed = ''; - this.ariaReadOnly = ''; - this.ariaRequired = ''; - this.ariaRoleDescription = ''; - this.ariaRowCount = ''; - this.ariaRowIndex = ''; - this.ariaRowSpan = ''; - this.ariaSelected = ''; - this.ariaSetSize = ''; - this.ariaSort = ''; - this.ariaValueMax = ''; - this.ariaValueMin = ''; - this.ariaValueNow = ''; - this.ariaValueText = ''; - this.role = ''; - this.form = null; - this.labels = []; - this.states = new Set(); - this.validationMessage = ''; - this.validity = {}; - this.willValidate = true; - this.__host = _host; - } - checkValidity() { - // TODO(augustjk) Consider actually implementing logic. - // See https://github.com/lit/lit/issues/3740 - console.warn('`ElementInternals.checkValidity()` was called on the server.' + - 'This method always returns true.'); - return true; - } - reportValidity() { - return true; - } - setFormValue() { } - setValidity() { } - }; - - const attributes = new WeakMap(); - const attributesForElement = element => { - let attrs = attributes.get(element); - if (attrs === undefined) { - attributes.set(element, attrs = new Map()); - } - return attrs; - }; - const ElementShim = class Element { - constructor() { - this.__shadowRootMode = null; - this.__shadowRoot = null; - this.__internals = null; - } - get attributes() { - return Array.from(attributesForElement(this)).map(([name, value]) => ({ - name, - value - })); - } - get shadowRoot() { - if (this.__shadowRootMode === "closed") { - return null; - } - return this.__shadowRoot; - } - get localName() { - return this.constructor.__localName; - } - get tagName() { - return this.localName?.toUpperCase(); - } - setAttribute(name, value) { - attributesForElement(this).set(name, String(value)); - } - removeAttribute(name) { - attributesForElement(this).delete(name); - } - toggleAttribute(name, force) { - if (this.hasAttribute(name)) { - if (force === undefined || !force) { - this.removeAttribute(name); - return false; - } - } else { - if (force === undefined || force) { - this.setAttribute(name, ""); - return true; - } else { - return false; - } - } - return true; - } - hasAttribute(name) { - return attributesForElement(this).has(name); - } - attachShadow(init) { - const shadowRoot = { - host: this - }; - this.__shadowRootMode = init.mode; - if (init && init.mode === "open") { - this.__shadowRoot = shadowRoot; - } - return shadowRoot; - } - attachInternals() { - if (this.__internals !== null) { - throw new Error(`Failed to execute 'attachInternals' on 'HTMLElement': ` + `ElementInternals for the specified element was already attached.`); - } - const internals = new ElementInternalsShim(this); - this.__internals = internals; - return internals; - } - getAttribute(name) { - const value = attributesForElement(this).get(name); - return value ?? null; - } - }; - const ElementShimWithRealType = ElementShim; - const HTMLElementShim = class HTMLElement extends ElementShim {}; - const HTMLElementShimWithRealType = HTMLElementShim; - const CustomElementRegistryShim = class CustomElementRegistry { - constructor() { - this.__definitions = new Map(); - } - define(name, ctor) { - if (this.__definitions.has(name)) { - { - throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': ` + `the name "${name}" has already been used with this registry`); - } - } - ctor.__localName = name; - this.__definitions.set(name, { - ctor, - observedAttributes: ctor.observedAttributes ?? [] - }); - } - get(name) { - const definition = this.__definitions.get(name); - return definition?.ctor; - } - }; - const CustomElementRegistryShimWithRealType = CustomElementRegistryShim; - const customElements$1 = new CustomElementRegistryShimWithRealType(); - - /* eslint-disable max-classes-per-file */ - globalThis.HTMLElement ??= HTMLElementShimWithRealType; - globalThis.Element ??= ElementShimWithRealType; - globalThis.customElements ??= customElements$1; - class NodeShim { - } - globalThis.Node ??= NodeShim; - class FileListShim { - } - globalThis.FileList ??= FileListShim; - var class2type = {}; var hasOwn = class2type.hasOwnProperty; var toString = class2type.toString; @@ -3011,7 +2810,7 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - var t$1;const i$1=globalThis,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=void 0===i$1.document?{createTreeWalker:()=>({})}: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,x=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),T=x(1),b=x(2),w=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 x=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+x):s+n+(-2===v?(e.push(void 0),i):x);}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!==w,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 k(i.insertBefore(u$1(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; + 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}; /** * @license @@ -3024,20 +2823,20 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const {I:l$1}=Z,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$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;}}; /** * @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$1=0,A=p$1.length-1;for(;j<=k&&w$1<=A;)if(null===a$1[j])j++;else if(null===a$1[k])k--;else if(h[j]===v[w$1])m$1[w$1]=f(a$1[j],p$1[w$1]),j++,w$1++;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$1])m$1[w$1]=f(a$1[k],p$1[w$1]),c$1(s,a$1[j],a$1[k]),k--,w$1++;else if(void 0===y&&(y=u(v,w$1,A),x=u(h,j,k)),y.has(h[j]))if(y.has(h[k])){const e=x.get(v[w$1]),t=void 0!==e?a$1[e]:null;if(null===t){const e=c$1(s,a$1[j]);f(e,p$1[w$1]),m$1[w$1]=e;}else m$1[w$1]=f(t,p$1[w$1]),c$1(s,a$1[j],t),a$1[e]=null;w$1++;}else p(a$1[k]),k--;else p(a$1[j]),j++;for(;w$1<=A;){const e=c$1(s,m$1[A+1]);f(e,p$1[w$1]),m$1[w$1++]=e;}for(;j<=k;){const e=a$1[j++];null!==e&&p(e);}return this.ut=v,a(s,m$1),w}}); + 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}}); /** * @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 w}}); + */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}}); /** * @license @@ -3049,11 +2848,11 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * @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===w)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{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; const effectiveHtml = (strings, ...values) => { const litStatic = getFeature("LitStatic"); - const fn = litStatic ? litStatic.html : T; + const fn = litStatic ? litStatic.html : x; return fn(strings, ...values); }; const effectiveSvg = (strings, ...values) => { @@ -3066,7 +2865,7 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor if (openUI5Enablement) { templateResult = openUI5Enablement.wrapTemplateResultInBusyMarkup(effectiveHtml, options.host, templateResult); } - B(templateResult, container, options); + D(templateResult, container, options); }; const scopeTag = (tag, tags, suffix) => { const litStatic = getFeature("LitStatic"); diff --git a/packages/ui5-tooling-modules/test/__snap__/484e54c0/@stomp/stompjs.js b/packages/ui5-tooling-modules/test/__snap__/484e54c0/@stomp/stompjs.js index 3107b43ad..2b8ea236b 100644 --- a/packages/ui5-tooling-modules/test/__snap__/484e54c0/@stomp/stompjs.js +++ b/packages/ui5-tooling-modules/test/__snap__/484e54c0/@stomp/stompjs.js @@ -1,1892 +1,1877 @@ -sap.ui.define((function () { 'use strict'; +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 : {}; + /** + * Some byte values, used as per STOMP specifications. + * + * Part of `@stomp/stompjs`. + * + * @internal + */ + const BYTE = { + // LINEFEED byte (octet 10) + LF: '\x0A', + // NULL byte (octet 0) + NULL: '\x00', + }; - var stomp_umd = {exports: {}}; + /** + * Frame class represents a STOMP frame. + * + * @internal + */ + class FrameImpl { + /** + * Frame constructor. `command`, `headers` and `body` are available as properties. + * + * @internal + */ + constructor(params) { + const { command, headers, body, binaryBody, escapeHeaderValues, skipContentLengthHeader, } = params; + this.command = command; + this.headers = Object.assign({}, headers || {}); + if (binaryBody) { + this._binaryBody = binaryBody; + this.isBinaryBody = true; + } + else { + this._body = body || ''; + this.isBinaryBody = false; + } + this.escapeHeaderValues = escapeHeaderValues || false; + this.skipContentLengthHeader = skipContentLengthHeader || false; + } + /** + * body of the frame + */ + get body() { + if (!this._body && this.isBinaryBody) { + this._body = new TextDecoder().decode(this._binaryBody); + } + return this._body || ''; + } + /** + * body as Uint8Array + */ + get binaryBody() { + if (!this._binaryBody && !this.isBinaryBody) { + this._binaryBody = new TextEncoder().encode(this._body); + } + // At this stage it will definitely have a valid value + return this._binaryBody; + } + /** + * deserialize a STOMP Frame from raw data. + * + * @internal + */ + static fromRawFrame(rawFrame, escapeHeaderValues) { + const headers = {}; + const trim = (str) => str.replace(/^\s+|\s+$/g, ''); + // In case of repeated headers, as per standards, first value need to be used + for (const header of rawFrame.headers.reverse()) { + header.indexOf(':'); + const key = trim(header[0]); + let value = trim(header[1]); + if (escapeHeaderValues && + rawFrame.command !== 'CONNECT' && + rawFrame.command !== 'CONNECTED') { + value = FrameImpl.hdrValueUnEscape(value); + } + headers[key] = value; + } + return new FrameImpl({ + command: rawFrame.command, + headers, + binaryBody: rawFrame.binaryBody, + escapeHeaderValues, + }); + } + /** + * @internal + */ + toString() { + return this.serializeCmdAndHeaders(); + } + /** + * serialize this Frame in a format suitable to be passed to WebSocket. + * If the body is string the output will be string. + * If the body is binary (i.e. of type Unit8Array) it will be serialized to ArrayBuffer. + * + * @internal + */ + serialize() { + const cmdAndHeaders = this.serializeCmdAndHeaders(); + if (this.isBinaryBody) { + return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer; + } + else { + return cmdAndHeaders + this._body + BYTE.NULL; + } + } + serializeCmdAndHeaders() { + const lines = [this.command]; + if (this.skipContentLengthHeader) { + delete this.headers['content-length']; + } + for (const name of Object.keys(this.headers || {})) { + const value = this.headers[name]; + if (this.escapeHeaderValues && + this.command !== 'CONNECT' && + this.command !== 'CONNECTED') { + lines.push(`${name}:${FrameImpl.hdrValueEscape(`${value}`)}`); + } + else { + lines.push(`${name}:${value}`); + } + } + if (this.isBinaryBody || + (!this.isBodyEmpty() && !this.skipContentLengthHeader)) { + lines.push(`content-length:${this.bodyLength()}`); + } + return lines.join(BYTE.LF) + BYTE.LF + BYTE.LF; + } + isBodyEmpty() { + return this.bodyLength() === 0; + } + bodyLength() { + const binaryBody = this.binaryBody; + return binaryBody ? binaryBody.length : 0; + } + /** + * Compute the size of a UTF-8 string by counting its number of bytes + * (and not the number of characters composing the string) + */ + static sizeOfUTF8(s) { + return s ? new TextEncoder().encode(s).length : 0; + } + static toUnit8Array(cmdAndHeaders, binaryBody) { + const uint8CmdAndHeaders = new TextEncoder().encode(cmdAndHeaders); + const nullTerminator = new Uint8Array([0]); + const uint8Frame = new Uint8Array(uint8CmdAndHeaders.length + binaryBody.length + nullTerminator.length); + uint8Frame.set(uint8CmdAndHeaders); + uint8Frame.set(binaryBody, uint8CmdAndHeaders.length); + uint8Frame.set(nullTerminator, uint8CmdAndHeaders.length + binaryBody.length); + return uint8Frame; + } + /** + * Serialize a STOMP frame as per STOMP standards, suitable to be sent to the STOMP broker. + * + * @internal + */ + static marshall(params) { + const frame = new FrameImpl(params); + return frame.serialize(); + } + /** + * Escape header values + */ + static hdrValueEscape(str) { + return str + .replace(/\\/g, '\\\\') + .replace(/\r/g, '\\r') + .replace(/\n/g, '\\n') + .replace(/:/g, '\\c'); + } + /** + * UnEscape header values + */ + static hdrValueUnEscape(str) { + return str + .replace(/\\r/g, '\r') + .replace(/\\n/g, '\n') + .replace(/\\c/g, ':') + .replace(/\\\\/g, '\\'); + } + } - (function (module, exports) { - (function (global, factory) { - factory(exports) ; - })(commonjsGlobal, (function (exports) { - /** - * Some byte values, used as per STOMP specifications. - * - * Part of `@stomp/stompjs`. - * - * @internal - */ - const BYTE = { - // LINEFEED byte (octet 10) - LF: '\x0A', - // NULL byte (octet 0) - NULL: '\x00', - }; + /** + * @internal + */ + const NULL = 0; + /** + * @internal + */ + const LF = 10; + /** + * @internal + */ + const CR = 13; + /** + * @internal + */ + const COLON = 58; + /** + * This is an evented, rec descent parser. + * A stream of Octets can be passed and whenever it recognizes + * a complete Frame or an incoming ping it will invoke the registered callbacks. + * + * All incoming Octets are fed into _onByte function. + * Depending on current state the _onByte function keeps changing. + * Depending on the state it keeps accumulating into _token and _results. + * State is indicated by current value of _onByte, all states are named as _collect. + * + * STOMP standards https://stomp.github.io/stomp-specification-1.2.html + * imply that all lengths are considered in bytes (instead of string lengths). + * So, before actual parsing, if the incoming data is String it is converted to Octets. + * This allows faithful implementation of the protocol and allows NULL Octets to be present in the body. + * + * There is no peek function on the incoming data. + * When a state change occurs based on an Octet without consuming the Octet, + * the Octet, after state change, is fed again (_reinjectByte). + * This became possible as the state change can be determined by inspecting just one Octet. + * + * There are two modes to collect the body, if content-length header is there then it by counting Octets + * otherwise it is determined by NULL terminator. + * + * Following the standards, the command and headers are converted to Strings + * and the body is returned as Octets. + * Headers are returned as an array and not as Hash - to allow multiple occurrence of an header. + * + * This parser does not use Regular Expressions as that can only operate on Strings. + * + * It handles if multiple STOMP frames are given as one chunk, a frame is split into multiple chunks, or + * any combination there of. The parser remembers its state (any partial frame) and continues when a new chunk + * is pushed. + * + * Typically the higher level function will convert headers to Hash, handle unescaping of header values + * (which is protocol version specific), and convert body to text. + * + * Check the parser.spec.js to understand cases that this parser is supposed to handle. + * + * Part of `@stomp/stompjs`. + * + * @internal + */ + class Parser { + constructor(onFrame, onIncomingPing) { + this.onFrame = onFrame; + this.onIncomingPing = onIncomingPing; + this._encoder = new TextEncoder(); + this._decoder = new TextDecoder(); + this._token = []; + this._initState(); + } + parseChunk(segment, appendMissingNULLonIncoming = false) { + let chunk; + if (typeof segment === 'string') { + chunk = this._encoder.encode(segment); + } + else { + chunk = new Uint8Array(segment); + } + // See https://github.com/stomp-js/stompjs/issues/89 + // Remove when underlying issue is fixed. + // + // Send a NULL byte, if the last byte of a Text frame was not NULL.F + if (appendMissingNULLonIncoming && chunk[chunk.length - 1] !== 0) { + const chunkWithNull = new Uint8Array(chunk.length + 1); + chunkWithNull.set(chunk, 0); + chunkWithNull[chunk.length] = 0; + chunk = chunkWithNull; + } + // tslint:disable-next-line:prefer-for-of + for (let i = 0; i < chunk.length; i++) { + const byte = chunk[i]; + this._onByte(byte); + } + } + // The following implements a simple Rec Descent Parser. + // The grammar is simple and just one byte tells what should be the next state + _collectFrame(byte) { + if (byte === NULL) { + // Ignore + return; + } + if (byte === CR) { + // Ignore CR + return; + } + if (byte === LF) { + // Incoming Ping + this.onIncomingPing(); + return; + } + this._onByte = this._collectCommand; + this._reinjectByte(byte); + } + _collectCommand(byte) { + if (byte === CR) { + // Ignore CR + return; + } + if (byte === LF) { + this._results.command = this._consumeTokenAsUTF8(); + this._onByte = this._collectHeaders; + return; + } + this._consumeByte(byte); + } + _collectHeaders(byte) { + if (byte === CR) { + // Ignore CR + return; + } + if (byte === LF) { + this._setupCollectBody(); + return; + } + this._onByte = this._collectHeaderKey; + this._reinjectByte(byte); + } + _reinjectByte(byte) { + this._onByte(byte); + } + _collectHeaderKey(byte) { + if (byte === COLON) { + this._headerKey = this._consumeTokenAsUTF8(); + this._onByte = this._collectHeaderValue; + return; + } + this._consumeByte(byte); + } + _collectHeaderValue(byte) { + if (byte === CR) { + // Ignore CR + return; + } + if (byte === LF) { + this._results.headers.push([ + this._headerKey, + this._consumeTokenAsUTF8(), + ]); + this._headerKey = undefined; + this._onByte = this._collectHeaders; + return; + } + this._consumeByte(byte); + } + _setupCollectBody() { + const contentLengthHeader = this._results.headers.filter((header) => { + return header[0] === 'content-length'; + })[0]; + if (contentLengthHeader) { + this._bodyBytesRemaining = parseInt(contentLengthHeader[1], 10); + this._onByte = this._collectBodyFixedSize; + } + else { + this._onByte = this._collectBodyNullTerminated; + } + } + _collectBodyNullTerminated(byte) { + if (byte === NULL) { + this._retrievedBody(); + return; + } + this._consumeByte(byte); + } + _collectBodyFixedSize(byte) { + // It is post decrement, so that we discard the trailing NULL octet + if (this._bodyBytesRemaining-- === 0) { + this._retrievedBody(); + return; + } + this._consumeByte(byte); + } + _retrievedBody() { + this._results.binaryBody = this._consumeTokenAsRaw(); + try { + this.onFrame(this._results); + } + catch (e) { + console.log(`Ignoring an exception thrown by a frame handler. Original exception: `, e); + } + this._initState(); + } + // Rec Descent Parser helpers + _consumeByte(byte) { + this._token.push(byte); + } + _consumeTokenAsUTF8() { + return this._decoder.decode(this._consumeTokenAsRaw()); + } + _consumeTokenAsRaw() { + const rawResult = new Uint8Array(this._token); + this._token = []; + return rawResult; + } + _initState() { + this._results = { + command: undefined, + headers: [], + binaryBody: undefined, + }; + this._token = []; + this._headerKey = undefined; + this._onByte = this._collectFrame; + } + } - /** - * Frame class represents a STOMP frame. - * - * @internal - */ - class FrameImpl { - /** - * Frame constructor. `command`, `headers` and `body` are available as properties. - * - * @internal - */ - constructor(params) { - const { command, headers, body, binaryBody, escapeHeaderValues, skipContentLengthHeader, } = params; - this.command = command; - this.headers = Object.assign({}, headers || {}); - if (binaryBody) { - this._binaryBody = binaryBody; - this.isBinaryBody = true; - } - else { - this._body = body || ''; - this.isBinaryBody = false; - } - this.escapeHeaderValues = escapeHeaderValues || false; - this.skipContentLengthHeader = skipContentLengthHeader || false; - } - /** - * body of the frame - */ - get body() { - if (!this._body && this.isBinaryBody) { - this._body = new TextDecoder().decode(this._binaryBody); - } - return this._body || ''; - } - /** - * body as Uint8Array - */ - get binaryBody() { - if (!this._binaryBody && !this.isBinaryBody) { - this._binaryBody = new TextEncoder().encode(this._body); - } - // At this stage it will definitely have a valid value - return this._binaryBody; - } - /** - * deserialize a STOMP Frame from raw data. - * - * @internal - */ - static fromRawFrame(rawFrame, escapeHeaderValues) { - const headers = {}; - const trim = (str) => str.replace(/^\s+|\s+$/g, ''); - // In case of repeated headers, as per standards, first value need to be used - for (const header of rawFrame.headers.reverse()) { - header.indexOf(':'); - const key = trim(header[0]); - let value = trim(header[1]); - if (escapeHeaderValues && - rawFrame.command !== 'CONNECT' && - rawFrame.command !== 'CONNECTED') { - value = FrameImpl.hdrValueUnEscape(value); - } - headers[key] = value; - } - return new FrameImpl({ - command: rawFrame.command, - headers, - binaryBody: rawFrame.binaryBody, - escapeHeaderValues, - }); - } - /** - * @internal - */ - toString() { - return this.serializeCmdAndHeaders(); - } - /** - * serialize this Frame in a format suitable to be passed to WebSocket. - * If the body is string the output will be string. - * If the body is binary (i.e. of type Unit8Array) it will be serialized to ArrayBuffer. - * - * @internal - */ - serialize() { - const cmdAndHeaders = this.serializeCmdAndHeaders(); - if (this.isBinaryBody) { - return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer; - } - else { - return cmdAndHeaders + this._body + BYTE.NULL; - } - } - serializeCmdAndHeaders() { - const lines = [this.command]; - if (this.skipContentLengthHeader) { - delete this.headers['content-length']; - } - for (const name of Object.keys(this.headers || {})) { - const value = this.headers[name]; - if (this.escapeHeaderValues && - this.command !== 'CONNECT' && - this.command !== 'CONNECTED') { - lines.push(`${name}:${FrameImpl.hdrValueEscape(`${value}`)}`); - } - else { - lines.push(`${name}:${value}`); - } - } - if (this.isBinaryBody || - (!this.isBodyEmpty() && !this.skipContentLengthHeader)) { - lines.push(`content-length:${this.bodyLength()}`); - } - return lines.join(BYTE.LF) + BYTE.LF + BYTE.LF; - } - isBodyEmpty() { - return this.bodyLength() === 0; - } - bodyLength() { - const binaryBody = this.binaryBody; - return binaryBody ? binaryBody.length : 0; - } - /** - * Compute the size of a UTF-8 string by counting its number of bytes - * (and not the number of characters composing the string) - */ - static sizeOfUTF8(s) { - return s ? new TextEncoder().encode(s).length : 0; - } - static toUnit8Array(cmdAndHeaders, binaryBody) { - const uint8CmdAndHeaders = new TextEncoder().encode(cmdAndHeaders); - const nullTerminator = new Uint8Array([0]); - const uint8Frame = new Uint8Array(uint8CmdAndHeaders.length + binaryBody.length + nullTerminator.length); - uint8Frame.set(uint8CmdAndHeaders); - uint8Frame.set(binaryBody, uint8CmdAndHeaders.length); - uint8Frame.set(nullTerminator, uint8CmdAndHeaders.length + binaryBody.length); - return uint8Frame; - } - /** - * Serialize a STOMP frame as per STOMP standards, suitable to be sent to the STOMP broker. - * - * @internal - */ - static marshall(params) { - const frame = new FrameImpl(params); - return frame.serialize(); - } - /** - * Escape header values - */ - static hdrValueEscape(str) { - return str - .replace(/\\/g, '\\\\') - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n') - .replace(/:/g, '\\c'); - } - /** - * UnEscape header values - */ - static hdrValueUnEscape(str) { - return str - .replace(/\\r/g, '\r') - .replace(/\\n/g, '\n') - .replace(/\\c/g, ':') - .replace(/\\\\/g, '\\'); - } - } + /** + * Possible states for the IStompSocket + */ + exports.StompSocketState = void 0; + (function (StompSocketState) { + StompSocketState[StompSocketState["CONNECTING"] = 0] = "CONNECTING"; + StompSocketState[StompSocketState["OPEN"] = 1] = "OPEN"; + StompSocketState[StompSocketState["CLOSING"] = 2] = "CLOSING"; + StompSocketState[StompSocketState["CLOSED"] = 3] = "CLOSED"; + })(exports.StompSocketState = exports.StompSocketState || (exports.StompSocketState = {})); + /** + * Possible activation state + */ + exports.ActivationState = void 0; + (function (ActivationState) { + ActivationState[ActivationState["ACTIVE"] = 0] = "ACTIVE"; + ActivationState[ActivationState["DEACTIVATING"] = 1] = "DEACTIVATING"; + ActivationState[ActivationState["INACTIVE"] = 2] = "INACTIVE"; + })(exports.ActivationState = exports.ActivationState || (exports.ActivationState = {})); - /** - * @internal - */ - const NULL = 0; - /** - * @internal - */ - const LF = 10; - /** - * @internal - */ - const CR = 13; - /** - * @internal - */ - const COLON = 58; - /** - * This is an evented, rec descent parser. - * A stream of Octets can be passed and whenever it recognizes - * a complete Frame or an incoming ping it will invoke the registered callbacks. - * - * All incoming Octets are fed into _onByte function. - * Depending on current state the _onByte function keeps changing. - * Depending on the state it keeps accumulating into _token and _results. - * State is indicated by current value of _onByte, all states are named as _collect. - * - * STOMP standards https://stomp.github.io/stomp-specification-1.2.html - * imply that all lengths are considered in bytes (instead of string lengths). - * So, before actual parsing, if the incoming data is String it is converted to Octets. - * This allows faithful implementation of the protocol and allows NULL Octets to be present in the body. - * - * There is no peek function on the incoming data. - * When a state change occurs based on an Octet without consuming the Octet, - * the Octet, after state change, is fed again (_reinjectByte). - * This became possible as the state change can be determined by inspecting just one Octet. - * - * There are two modes to collect the body, if content-length header is there then it by counting Octets - * otherwise it is determined by NULL terminator. - * - * Following the standards, the command and headers are converted to Strings - * and the body is returned as Octets. - * Headers are returned as an array and not as Hash - to allow multiple occurrence of an header. - * - * This parser does not use Regular Expressions as that can only operate on Strings. - * - * It handles if multiple STOMP frames are given as one chunk, a frame is split into multiple chunks, or - * any combination there of. The parser remembers its state (any partial frame) and continues when a new chunk - * is pushed. - * - * Typically the higher level function will convert headers to Hash, handle unescaping of header values - * (which is protocol version specific), and convert body to text. - * - * Check the parser.spec.js to understand cases that this parser is supposed to handle. - * - * Part of `@stomp/stompjs`. - * - * @internal - */ - class Parser { - constructor(onFrame, onIncomingPing) { - this.onFrame = onFrame; - this.onIncomingPing = onIncomingPing; - this._encoder = new TextEncoder(); - this._decoder = new TextDecoder(); - this._token = []; - this._initState(); - } - parseChunk(segment, appendMissingNULLonIncoming = false) { - let chunk; - if (typeof segment === 'string') { - chunk = this._encoder.encode(segment); - } - else { - chunk = new Uint8Array(segment); - } - // See https://github.com/stomp-js/stompjs/issues/89 - // Remove when underlying issue is fixed. - // - // Send a NULL byte, if the last byte of a Text frame was not NULL.F - if (appendMissingNULLonIncoming && chunk[chunk.length - 1] !== 0) { - const chunkWithNull = new Uint8Array(chunk.length + 1); - chunkWithNull.set(chunk, 0); - chunkWithNull[chunk.length] = 0; - chunk = chunkWithNull; - } - // tslint:disable-next-line:prefer-for-of - for (let i = 0; i < chunk.length; i++) { - const byte = chunk[i]; - this._onByte(byte); - } - } - // The following implements a simple Rec Descent Parser. - // The grammar is simple and just one byte tells what should be the next state - _collectFrame(byte) { - if (byte === NULL) { - // Ignore - return; - } - if (byte === CR) { - // Ignore CR - return; - } - if (byte === LF) { - // Incoming Ping - this.onIncomingPing(); - return; - } - this._onByte = this._collectCommand; - this._reinjectByte(byte); - } - _collectCommand(byte) { - if (byte === CR) { - // Ignore CR - return; - } - if (byte === LF) { - this._results.command = this._consumeTokenAsUTF8(); - this._onByte = this._collectHeaders; - return; - } - this._consumeByte(byte); - } - _collectHeaders(byte) { - if (byte === CR) { - // Ignore CR - return; - } - if (byte === LF) { - this._setupCollectBody(); - return; - } - this._onByte = this._collectHeaderKey; - this._reinjectByte(byte); - } - _reinjectByte(byte) { - this._onByte(byte); - } - _collectHeaderKey(byte) { - if (byte === COLON) { - this._headerKey = this._consumeTokenAsUTF8(); - this._onByte = this._collectHeaderValue; - return; - } - this._consumeByte(byte); - } - _collectHeaderValue(byte) { - if (byte === CR) { - // Ignore CR - return; - } - if (byte === LF) { - this._results.headers.push([ - this._headerKey, - this._consumeTokenAsUTF8(), - ]); - this._headerKey = undefined; - this._onByte = this._collectHeaders; - return; - } - this._consumeByte(byte); - } - _setupCollectBody() { - const contentLengthHeader = this._results.headers.filter((header) => { - return header[0] === 'content-length'; - })[0]; - if (contentLengthHeader) { - this._bodyBytesRemaining = parseInt(contentLengthHeader[1], 10); - this._onByte = this._collectBodyFixedSize; - } - else { - this._onByte = this._collectBodyNullTerminated; - } - } - _collectBodyNullTerminated(byte) { - if (byte === NULL) { - this._retrievedBody(); - return; - } - this._consumeByte(byte); - } - _collectBodyFixedSize(byte) { - // It is post decrement, so that we discard the trailing NULL octet - if (this._bodyBytesRemaining-- === 0) { - this._retrievedBody(); - return; - } - this._consumeByte(byte); - } - _retrievedBody() { - this._results.binaryBody = this._consumeTokenAsRaw(); - try { - this.onFrame(this._results); - } - catch (e) { - console.log(`Ignoring an exception thrown by a frame handler. Original exception: `, e); - } - this._initState(); - } - // Rec Descent Parser helpers - _consumeByte(byte) { - this._token.push(byte); - } - _consumeTokenAsUTF8() { - return this._decoder.decode(this._consumeTokenAsRaw()); - } - _consumeTokenAsRaw() { - const rawResult = new Uint8Array(this._token); - this._token = []; - return rawResult; - } - _initState() { - this._results = { - command: undefined, - headers: [], - binaryBody: undefined, - }; - this._token = []; - this._headerKey = undefined; - this._onByte = this._collectFrame; - } - } + /** + * Supported STOMP versions + * + * Part of `@stomp/stompjs`. + */ + class Versions { + /** + * Takes an array of versions, typical elements '1.2', '1.1', or '1.0' + * + * You will be creating an instance of this class if you want to override + * supported versions to be declared during STOMP handshake. + */ + constructor(versions) { + this.versions = versions; + } + /** + * Used as part of CONNECT STOMP Frame + */ + supportedVersions() { + return this.versions.join(','); + } + /** + * Used while creating a WebSocket + */ + protocolVersions() { + return this.versions.map(x => `v${x.replace('.', '')}.stomp`); + } + } + /** + * Indicates protocol version 1.0 + */ + Versions.V1_0 = '1.0'; + /** + * Indicates protocol version 1.1 + */ + Versions.V1_1 = '1.1'; + /** + * Indicates protocol version 1.2 + */ + Versions.V1_2 = '1.2'; + /** + * @internal + */ + Versions.default = new Versions([ + Versions.V1_2, + Versions.V1_1, + Versions.V1_0, + ]); - /** - * Possible states for the IStompSocket - */ - exports.StompSocketState = void 0; - (function (StompSocketState) { - StompSocketState[StompSocketState["CONNECTING"] = 0] = "CONNECTING"; - StompSocketState[StompSocketState["OPEN"] = 1] = "OPEN"; - StompSocketState[StompSocketState["CLOSING"] = 2] = "CLOSING"; - StompSocketState[StompSocketState["CLOSED"] = 3] = "CLOSED"; - })(exports.StompSocketState = exports.StompSocketState || (exports.StompSocketState = {})); - /** - * Possible activation state - */ - exports.ActivationState = void 0; - (function (ActivationState) { - ActivationState[ActivationState["ACTIVE"] = 0] = "ACTIVE"; - ActivationState[ActivationState["DEACTIVATING"] = 1] = "DEACTIVATING"; - ActivationState[ActivationState["INACTIVE"] = 2] = "INACTIVE"; - })(exports.ActivationState = exports.ActivationState || (exports.ActivationState = {})); + /** + * @internal + */ + function augmentWebsocket(webSocket, debug) { + webSocket.terminate = function () { + const noOp = () => { }; + // set all callbacks to no op + this.onerror = noOp; + this.onmessage = noOp; + this.onopen = noOp; + const ts = new Date(); + const id = Math.random().toString().substring(2, 8); // A simulated id + const origOnClose = this.onclose; + // Track delay in actual closure of the socket + this.onclose = closeEvent => { + const delay = new Date().getTime() - ts.getTime(); + debug(`Discarded socket (#${id}) closed after ${delay}ms, with code/reason: ${closeEvent.code}/${closeEvent.reason}`); + }; + this.close(); + origOnClose?.call(webSocket, { + code: 4001, + reason: `Quick discarding socket (#${id}) without waiting for the shutdown sequence.`, + wasClean: false, + }); + }; + } - /** - * Supported STOMP versions - * - * Part of `@stomp/stompjs`. - */ - class Versions { - /** - * Takes an array of versions, typical elements '1.2', '1.1', or '1.0' - * - * You will be creating an instance of this class if you want to override - * supported versions to be declared during STOMP handshake. - */ - constructor(versions) { - this.versions = versions; - } - /** - * Used as part of CONNECT STOMP Frame - */ - supportedVersions() { - return this.versions.join(','); - } - /** - * Used while creating a WebSocket - */ - protocolVersions() { - return this.versions.map(x => `v${x.replace('.', '')}.stomp`); - } - } - /** - * Indicates protocol version 1.0 - */ - Versions.V1_0 = '1.0'; - /** - * Indicates protocol version 1.1 - */ - Versions.V1_1 = '1.1'; - /** - * Indicates protocol version 1.2 - */ - Versions.V1_2 = '1.2'; - /** - * @internal - */ - Versions.default = new Versions([ - Versions.V1_2, - Versions.V1_1, - Versions.V1_0, - ]); + /** + * The STOMP protocol handler + * + * Part of `@stomp/stompjs`. + * + * @internal + */ + class StompHandler { + constructor(_client, _webSocket, config) { + this._client = _client; + this._webSocket = _webSocket; + this._connected = false; + this._serverFrameHandlers = { + // [CONNECTED Frame](https://stomp.github.com/stomp-specification-1.2.html#CONNECTED_Frame) + CONNECTED: frame => { + this.debug(`connected to server ${frame.headers.server}`); + this._connected = true; + this._connectedVersion = frame.headers.version; + // STOMP version 1.2 needs header values to be escaped + if (this._connectedVersion === Versions.V1_2) { + this._escapeHeaderValues = true; + } + this._setupHeartbeat(frame.headers); + this.onConnect(frame); + }, + // [MESSAGE Frame](https://stomp.github.com/stomp-specification-1.2.html#MESSAGE) + MESSAGE: frame => { + // the callback is registered when the client calls + // `subscribe()`. + // If there is no registered subscription for the received message, + // the default `onUnhandledMessage` callback is used that the client can set. + // This is useful for subscriptions that are automatically created + // on the browser side (e.g. [RabbitMQ's temporary + // queues](https://www.rabbitmq.com/stomp.html)). + const subscription = frame.headers.subscription; + const onReceive = this._subscriptions[subscription] || this.onUnhandledMessage; + // bless the frame to be a Message + const message = frame; + const client = this; + const messageId = this._connectedVersion === Versions.V1_2 + ? message.headers.ack + : message.headers['message-id']; + // add `ack()` and `nack()` methods directly to the returned frame + // so that a simple call to `message.ack()` can acknowledge the message. + message.ack = (headers = {}) => { + return client.ack(messageId, subscription, headers); + }; + message.nack = (headers = {}) => { + return client.nack(messageId, subscription, headers); + }; + onReceive(message); + }, + // [RECEIPT Frame](https://stomp.github.com/stomp-specification-1.2.html#RECEIPT) + RECEIPT: frame => { + const callback = this._receiptWatchers[frame.headers['receipt-id']]; + if (callback) { + callback(frame); + // Server will acknowledge only once, remove the callback + delete this._receiptWatchers[frame.headers['receipt-id']]; + } + else { + this.onUnhandledReceipt(frame); + } + }, + // [ERROR Frame](https://stomp.github.com/stomp-specification-1.2.html#ERROR) + ERROR: frame => { + this.onStompError(frame); + }, + }; + // used to index subscribers + this._counter = 0; + // subscription callbacks indexed by subscriber's ID + this._subscriptions = {}; + // receipt-watchers indexed by receipts-ids + this._receiptWatchers = {}; + this._partialData = ''; + this._escapeHeaderValues = false; + this._lastServerActivityTS = Date.now(); + this.debug = config.debug; + this.stompVersions = config.stompVersions; + this.connectHeaders = config.connectHeaders; + this.disconnectHeaders = config.disconnectHeaders; + this.heartbeatIncoming = config.heartbeatIncoming; + this.heartbeatOutgoing = config.heartbeatOutgoing; + this.splitLargeFrames = config.splitLargeFrames; + this.maxWebSocketChunkSize = config.maxWebSocketChunkSize; + this.forceBinaryWSFrames = config.forceBinaryWSFrames; + this.logRawCommunication = config.logRawCommunication; + this.appendMissingNULLonIncoming = config.appendMissingNULLonIncoming; + this.discardWebsocketOnCommFailure = config.discardWebsocketOnCommFailure; + this.onConnect = config.onConnect; + this.onDisconnect = config.onDisconnect; + this.onStompError = config.onStompError; + this.onWebSocketClose = config.onWebSocketClose; + this.onWebSocketError = config.onWebSocketError; + this.onUnhandledMessage = config.onUnhandledMessage; + this.onUnhandledReceipt = config.onUnhandledReceipt; + this.onUnhandledFrame = config.onUnhandledFrame; + } + get connectedVersion() { + return this._connectedVersion; + } + get connected() { + return this._connected; + } + start() { + const parser = new Parser( + // On Frame + rawFrame => { + const frame = FrameImpl.fromRawFrame(rawFrame, this._escapeHeaderValues); + // if this.logRawCommunication is set, the rawChunk is logged at this._webSocket.onmessage + if (!this.logRawCommunication) { + this.debug(`<<< ${frame}`); + } + const serverFrameHandler = this._serverFrameHandlers[frame.command] || this.onUnhandledFrame; + serverFrameHandler(frame); + }, + // On Incoming Ping + () => { + this.debug('<<< PONG'); + }); + this._webSocket.onmessage = (evt) => { + this.debug('Received data'); + this._lastServerActivityTS = Date.now(); + if (this.logRawCommunication) { + const rawChunkAsString = evt.data instanceof ArrayBuffer + ? new TextDecoder().decode(evt.data) + : evt.data; + this.debug(`<<< ${rawChunkAsString}`); + } + parser.parseChunk(evt.data, this.appendMissingNULLonIncoming); + }; + this._webSocket.onclose = (closeEvent) => { + this.debug(`Connection closed to ${this._webSocket.url}`); + this._cleanUp(); + this.onWebSocketClose(closeEvent); + }; + this._webSocket.onerror = (errorEvent) => { + this.onWebSocketError(errorEvent); + }; + this._webSocket.onopen = () => { + // Clone before updating + const connectHeaders = Object.assign({}, this.connectHeaders); + this.debug('Web Socket Opened...'); + connectHeaders['accept-version'] = this.stompVersions.supportedVersions(); + connectHeaders['heart-beat'] = [ + this.heartbeatOutgoing, + this.heartbeatIncoming, + ].join(','); + this._transmit({ command: 'CONNECT', headers: connectHeaders }); + }; + } + _setupHeartbeat(headers) { + if (headers.version !== Versions.V1_1 && + headers.version !== Versions.V1_2) { + return; + } + // It is valid for the server to not send this header + // https://stomp.github.io/stomp-specification-1.2.html#Heart-beating + if (!headers['heart-beat']) { + return; + } + // heart-beat header received from the server looks like: + // + // heart-beat: sx, sy + const [serverOutgoing, serverIncoming] = headers['heart-beat'] + .split(',') + .map((v) => parseInt(v, 10)); + if (this.heartbeatOutgoing !== 0 && serverIncoming !== 0) { + const ttl = Math.max(this.heartbeatOutgoing, serverIncoming); + this.debug(`send PING every ${ttl}ms`); + this._pinger = setInterval(() => { + if (this._webSocket.readyState === exports.StompSocketState.OPEN) { + this._webSocket.send(BYTE.LF); + this.debug('>>> PING'); + } + }, ttl); + } + if (this.heartbeatIncoming !== 0 && serverOutgoing !== 0) { + const ttl = Math.max(this.heartbeatIncoming, serverOutgoing); + this.debug(`check PONG every ${ttl}ms`); + this._ponger = setInterval(() => { + const delta = Date.now() - this._lastServerActivityTS; + // We wait twice the TTL to be flexible on window's setInterval calls + if (delta > ttl * 2) { + this.debug(`did not receive server activity for the last ${delta}ms`); + this._closeOrDiscardWebsocket(); + } + }, ttl); + } + } + _closeOrDiscardWebsocket() { + if (this.discardWebsocketOnCommFailure) { + this.debug('Discarding websocket, the underlying socket may linger for a while'); + this.discardWebsocket(); + } + else { + this.debug('Issuing close on the websocket'); + this._closeWebsocket(); + } + } + forceDisconnect() { + if (this._webSocket) { + if (this._webSocket.readyState === exports.StompSocketState.CONNECTING || + this._webSocket.readyState === exports.StompSocketState.OPEN) { + this._closeOrDiscardWebsocket(); + } + } + } + _closeWebsocket() { + this._webSocket.onmessage = () => { }; // ignore messages + this._webSocket.close(); + } + discardWebsocket() { + if (typeof this._webSocket.terminate !== 'function') { + augmentWebsocket(this._webSocket, (msg) => this.debug(msg)); + } + // @ts-ignore - this method will be there at this stage + this._webSocket.terminate(); + } + _transmit(params) { + const { command, headers, body, binaryBody, skipContentLengthHeader } = params; + const frame = new FrameImpl({ + command, + headers, + body, + binaryBody, + escapeHeaderValues: this._escapeHeaderValues, + skipContentLengthHeader, + }); + let rawChunk = frame.serialize(); + if (this.logRawCommunication) { + this.debug(`>>> ${rawChunk}`); + } + else { + this.debug(`>>> ${frame}`); + } + if (this.forceBinaryWSFrames && typeof rawChunk === 'string') { + rawChunk = new TextEncoder().encode(rawChunk); + } + if (typeof rawChunk !== 'string' || !this.splitLargeFrames) { + this._webSocket.send(rawChunk); + } + else { + let out = rawChunk; + while (out.length > 0) { + const chunk = out.substring(0, this.maxWebSocketChunkSize); + out = out.substring(this.maxWebSocketChunkSize); + this._webSocket.send(chunk); + this.debug(`chunk sent = ${chunk.length}, remaining = ${out.length}`); + } + } + } + dispose() { + if (this.connected) { + try { + // clone before updating + const disconnectHeaders = Object.assign({}, this.disconnectHeaders); + if (!disconnectHeaders.receipt) { + disconnectHeaders.receipt = `close-${this._counter++}`; + } + this.watchForReceipt(disconnectHeaders.receipt, frame => { + this._closeWebsocket(); + this._cleanUp(); + this.onDisconnect(frame); + }); + this._transmit({ command: 'DISCONNECT', headers: disconnectHeaders }); + } + catch (error) { + this.debug(`Ignoring error during disconnect ${error}`); + } + } + else { + if (this._webSocket.readyState === exports.StompSocketState.CONNECTING || + this._webSocket.readyState === exports.StompSocketState.OPEN) { + this._closeWebsocket(); + } + } + } + _cleanUp() { + this._connected = false; + if (this._pinger) { + clearInterval(this._pinger); + this._pinger = undefined; + } + if (this._ponger) { + clearInterval(this._ponger); + this._ponger = undefined; + } + } + publish(params) { + const { destination, headers, body, binaryBody, skipContentLengthHeader } = params; + const hdrs = Object.assign({ destination }, headers); + this._transmit({ + command: 'SEND', + headers: hdrs, + body, + binaryBody, + skipContentLengthHeader, + }); + } + watchForReceipt(receiptId, callback) { + this._receiptWatchers[receiptId] = callback; + } + subscribe(destination, callback, headers = {}) { + headers = Object.assign({}, headers); + if (!headers.id) { + headers.id = `sub-${this._counter++}`; + } + headers.destination = destination; + this._subscriptions[headers.id] = callback; + this._transmit({ command: 'SUBSCRIBE', headers }); + const client = this; + return { + id: headers.id, + unsubscribe(hdrs) { + return client.unsubscribe(headers.id, hdrs); + }, + }; + } + unsubscribe(id, headers = {}) { + headers = Object.assign({}, headers); + delete this._subscriptions[id]; + headers.id = id; + this._transmit({ command: 'UNSUBSCRIBE', headers }); + } + begin(transactionId) { + const txId = transactionId || `tx-${this._counter++}`; + this._transmit({ + command: 'BEGIN', + headers: { + transaction: txId, + }, + }); + const client = this; + return { + id: txId, + commit() { + client.commit(txId); + }, + abort() { + client.abort(txId); + }, + }; + } + commit(transactionId) { + this._transmit({ + command: 'COMMIT', + headers: { + transaction: transactionId, + }, + }); + } + abort(transactionId) { + this._transmit({ + command: 'ABORT', + headers: { + transaction: transactionId, + }, + }); + } + ack(messageId, subscriptionId, headers = {}) { + headers = Object.assign({}, headers); + if (this._connectedVersion === Versions.V1_2) { + headers.id = messageId; + } + else { + headers['message-id'] = messageId; + } + headers.subscription = subscriptionId; + this._transmit({ command: 'ACK', headers }); + } + nack(messageId, subscriptionId, headers = {}) { + headers = Object.assign({}, headers); + if (this._connectedVersion === Versions.V1_2) { + headers.id = messageId; + } + else { + headers['message-id'] = messageId; + } + headers.subscription = subscriptionId; + return this._transmit({ command: 'NACK', headers }); + } + } - /** - * @internal - */ - function augmentWebsocket(webSocket, debug) { - webSocket.terminate = function () { - const noOp = () => { }; - // set all callbacks to no op - this.onerror = noOp; - this.onmessage = noOp; - this.onopen = noOp; - const ts = new Date(); - const id = Math.random().toString().substring(2, 8); // A simulated id - const origOnClose = this.onclose; - // Track delay in actual closure of the socket - this.onclose = closeEvent => { - const delay = new Date().getTime() - ts.getTime(); - debug(`Discarded socket (#${id}) closed after ${delay}ms, with code/reason: ${closeEvent.code}/${closeEvent.reason}`); - }; - this.close(); - origOnClose?.call(webSocket, { - code: 4001, - reason: `Quick discarding socket (#${id}) without waiting for the shutdown sequence.`, - wasClean: false, - }); - }; - } + /** + * STOMP Client Class. + * + * Part of `@stomp/stompjs`. + */ + class Client { + /** + * Create an instance. + */ + constructor(conf = {}) { + /** + * STOMP versions to attempt during STOMP handshake. By default, versions `1.2`, `1.1`, and `1.0` are attempted. + * + * Example: + * ```javascript + * // Try only versions 1.1 and 1.0 + * client.stompVersions = new Versions(['1.1', '1.0']) + * ``` + */ + this.stompVersions = Versions.default; + /** + * Will retry if Stomp connection is not established in specified milliseconds. + * Default 0, which switches off automatic reconnection. + */ + this.connectionTimeout = 0; + /** + * automatically reconnect with delay in milliseconds, set to 0 to disable. + */ + this.reconnectDelay = 5000; + /** + * Incoming heartbeat interval in milliseconds. Set to 0 to disable. + */ + this.heartbeatIncoming = 10000; + /** + * Outgoing heartbeat interval in milliseconds. Set to 0 to disable. + */ + this.heartbeatOutgoing = 10000; + /** + * This switches on a non-standard behavior while sending WebSocket packets. + * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}. + * Only Java Spring brokers seem to support this mode. + * + * WebSockets, by itself, split large (text) packets, + * so it is not needed with a truly compliant STOMP/WebSocket broker. + * Setting it for such a broker will cause large messages to fail. + * + * `false` by default. + * + * Binary frames are never split. + */ + this.splitLargeFrames = false; + /** + * See [splitLargeFrames]{@link Client#splitLargeFrames}. + * This has no effect if [splitLargeFrames]{@link Client#splitLargeFrames} is `false`. + */ + this.maxWebSocketChunkSize = 8 * 1024; + /** + * Usually the + * [type of WebSocket frame]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send#Parameters} + * is automatically decided by type of the payload. + * Default is `false`, which should work with all compliant brokers. + * + * Set this flag to force binary frames. + */ + this.forceBinaryWSFrames = false; + /** + * A bug in ReactNative chops a string on occurrence of a NULL. + * See issue [https://github.com/stomp-js/stompjs/issues/89]{@link https://github.com/stomp-js/stompjs/issues/89}. + * This makes incoming WebSocket messages invalid STOMP packets. + * Setting this flag attempts to reverse the damage by appending a NULL. + * If the broker splits a large message into multiple WebSocket messages, + * this flag will cause data loss and abnormal termination of connection. + * + * This is not an ideal solution, but a stop gap until the underlying issue is fixed at ReactNative library. + */ + this.appendMissingNULLonIncoming = false; + /** + * Browsers do not immediately close WebSockets when `.close` is issued. + * This may cause reconnection to take a significantly long time in case + * of some types of failures. + * In case of incoming heartbeat failure, this experimental flag instructs + * the library to discard the socket immediately + * (even before it is actually closed). + */ + this.discardWebsocketOnCommFailure = false; + /** + * Activation state. + * + * It will usually be ACTIVE or INACTIVE. + * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING. + */ + this.state = exports.ActivationState.INACTIVE; + // No op callbacks + const noOp = () => { }; + this.debug = noOp; + this.beforeConnect = noOp; + this.onConnect = noOp; + this.onDisconnect = noOp; + this.onUnhandledMessage = noOp; + this.onUnhandledReceipt = noOp; + this.onUnhandledFrame = noOp; + this.onStompError = noOp; + this.onWebSocketClose = noOp; + this.onWebSocketError = noOp; + this.logRawCommunication = false; + this.onChangeState = noOp; + // These parameters would typically get proper values before connect is called + this.connectHeaders = {}; + this._disconnectHeaders = {}; + // Apply configuration + this.configure(conf); + } + /** + * Underlying WebSocket instance, READONLY. + */ + get webSocket() { + return this._stompHandler?._webSocket; + } + /** + * Disconnection headers. + */ + get disconnectHeaders() { + return this._disconnectHeaders; + } + set disconnectHeaders(value) { + this._disconnectHeaders = value; + if (this._stompHandler) { + this._stompHandler.disconnectHeaders = this._disconnectHeaders; + } + } + /** + * `true` if there is an active connection to STOMP Broker + */ + get connected() { + return !!this._stompHandler && this._stompHandler.connected; + } + /** + * version of STOMP protocol negotiated with the server, READONLY + */ + get connectedVersion() { + return this._stompHandler ? this._stompHandler.connectedVersion : undefined; + } + /** + * if the client is active (connected or going to reconnect) + */ + get active() { + return this.state === exports.ActivationState.ACTIVE; + } + _changeState(state) { + this.state = state; + this.onChangeState(state); + } + /** + * Update configuration. + */ + configure(conf) { + // bulk assign all properties to this + Object.assign(this, conf); + } + /** + * Initiate the connection with the broker. + * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay}, + * it will keep trying to reconnect. + * + * Call [Client#deactivate]{@link Client#deactivate} to disconnect and stop reconnection attempts. + */ + activate() { + const _activate = () => { + if (this.active) { + this.debug('Already ACTIVE, ignoring request to activate'); + return; + } + this._changeState(exports.ActivationState.ACTIVE); + this._connect(); + }; + // if it is deactivating, wait for it to complete before activating. + if (this.state === exports.ActivationState.DEACTIVATING) { + this.debug('Waiting for deactivation to finish before activating'); + this.deactivate().then(() => { + _activate(); + }); + } + else { + _activate(); + } + } + async _connect() { + await this.beforeConnect(); + if (this._stompHandler) { + this.debug('There is already a stompHandler, skipping the call to connect'); + return; + } + if (!this.active) { + this.debug('Client has been marked inactive, will not attempt to connect'); + return; + } + // setup connection watcher + if (this.connectionTimeout > 0) { + // clear first + if (this._connectionWatcher) { + clearTimeout(this._connectionWatcher); + } + this._connectionWatcher = setTimeout(() => { + if (this.connected) { + return; + } + // Connection not established, close the underlying socket + // a reconnection will be attempted + this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`); + this.forceDisconnect(); + }, this.connectionTimeout); + } + this.debug('Opening Web Socket...'); + // Get the actual WebSocket (or a similar object) + const webSocket = this._createWebSocket(); + this._stompHandler = new StompHandler(this, webSocket, { + debug: this.debug, + stompVersions: this.stompVersions, + connectHeaders: this.connectHeaders, + disconnectHeaders: this._disconnectHeaders, + heartbeatIncoming: this.heartbeatIncoming, + heartbeatOutgoing: this.heartbeatOutgoing, + splitLargeFrames: this.splitLargeFrames, + maxWebSocketChunkSize: this.maxWebSocketChunkSize, + forceBinaryWSFrames: this.forceBinaryWSFrames, + logRawCommunication: this.logRawCommunication, + appendMissingNULLonIncoming: this.appendMissingNULLonIncoming, + discardWebsocketOnCommFailure: this.discardWebsocketOnCommFailure, + onConnect: frame => { + // Successfully connected, stop the connection watcher + if (this._connectionWatcher) { + clearTimeout(this._connectionWatcher); + this._connectionWatcher = undefined; + } + if (!this.active) { + this.debug('STOMP got connected while deactivate was issued, will disconnect now'); + this._disposeStompHandler(); + return; + } + this.onConnect(frame); + }, + onDisconnect: frame => { + this.onDisconnect(frame); + }, + onStompError: frame => { + this.onStompError(frame); + }, + onWebSocketClose: evt => { + this._stompHandler = undefined; // a new one will be created in case of a reconnect + if (this.state === exports.ActivationState.DEACTIVATING) { + // Mark deactivation complete + this._changeState(exports.ActivationState.INACTIVE); + } + // The callback is called before attempting to reconnect, this would allow the client + // to be `deactivated` in the callback. + this.onWebSocketClose(evt); + if (this.active) { + this._schedule_reconnect(); + } + }, + onWebSocketError: evt => { + this.onWebSocketError(evt); + }, + onUnhandledMessage: message => { + this.onUnhandledMessage(message); + }, + onUnhandledReceipt: frame => { + this.onUnhandledReceipt(frame); + }, + onUnhandledFrame: frame => { + this.onUnhandledFrame(frame); + }, + }); + this._stompHandler.start(); + } + _createWebSocket() { + let webSocket; + if (this.webSocketFactory) { + webSocket = this.webSocketFactory(); + } + else if (this.brokerURL) { + webSocket = new WebSocket(this.brokerURL, this.stompVersions.protocolVersions()); + } + else { + throw new Error('Either brokerURL or webSocketFactory must be provided'); + } + webSocket.binaryType = 'arraybuffer'; + return webSocket; + } + _schedule_reconnect() { + if (this.reconnectDelay > 0) { + this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`); + this._reconnector = setTimeout(() => { + this._connect(); + }, this.reconnectDelay); + } + } + /** + * Disconnect if connected and stop auto reconnect loop. + * Appropriate callbacks will be invoked if there is an underlying STOMP connection. + * + * This call is async. It will resolve immediately if there is no underlying active websocket, + * otherwise, it will resolve after the underlying websocket is properly disposed of. + * + * It is not an error to invoke this method more than once. + * Each of those would resolve on completion of deactivation. + * + * To reactivate, you can call [Client#activate]{@link Client#activate}. + * + * Experimental: pass `force: true` to immediately discard the underlying connection. + * This mode will skip both the STOMP and the Websocket shutdown sequences. + * In some cases, browsers take a long time in the Websocket shutdown + * if the underlying connection had gone stale. + * Using this mode can speed up. + * When this mode is used, the actual Websocket may linger for a while + * and the broker may not realize that the connection is no longer in use. + * + * It is possible to invoke this method initially without the `force` option + * and subsequently, say after a wait, with the `force` option. + */ + async deactivate(options = {}) { + const force = options.force || false; + const needToDispose = this.active; + let retPromise; + if (this.state === exports.ActivationState.INACTIVE) { + this.debug(`Already INACTIVE, nothing more to do`); + return Promise.resolve(); + } + this._changeState(exports.ActivationState.DEACTIVATING); + // Clear if a reconnection was scheduled + if (this._reconnector) { + clearTimeout(this._reconnector); + this._reconnector = undefined; + } + if (this._stompHandler && + // @ts-ignore - if there is a _stompHandler, there is the webSocket + this.webSocket.readyState !== exports.StompSocketState.CLOSED) { + const origOnWebSocketClose = this._stompHandler.onWebSocketClose; + // we need to wait for the underlying websocket to close + retPromise = new Promise((resolve, reject) => { + // @ts-ignore - there is a _stompHandler + this._stompHandler.onWebSocketClose = evt => { + origOnWebSocketClose(evt); + resolve(); + }; + }); + } + else { + // indicate that auto reconnect loop should terminate + this._changeState(exports.ActivationState.INACTIVE); + return Promise.resolve(); + } + if (force) { + this._stompHandler?.discardWebsocket(); + } + else if (needToDispose) { + this._disposeStompHandler(); + } + return retPromise; + } + /** + * Force disconnect if there is an active connection by directly closing the underlying WebSocket. + * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker. + * After forcing disconnect, automatic reconnect will be attempted. + * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well. + */ + forceDisconnect() { + if (this._stompHandler) { + this._stompHandler.forceDisconnect(); + } + } + _disposeStompHandler() { + // Dispose STOMP Handler + if (this._stompHandler) { + this._stompHandler.dispose(); + } + } + /** + * Send a message to a named destination. Refer to your STOMP broker documentation for types + * and naming of destinations. + * + * STOMP protocol specifies and suggests some headers and also allows broker-specific headers. + * + * `body` must be String. + * You will need to covert the payload to string in case it is not string (e.g. JSON). + * + * To send a binary message body, use `binaryBody` parameter. It should be a + * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). + * Sometimes brokers may not support binary frames out of the box. + * Please check your broker documentation. + * + * `content-length` header is automatically added to the STOMP Frame sent to the broker. + * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added. + * For binary messages, `content-length` header is always added. + * + * Caution: The broker will, most likely, report an error and disconnect + * if the message body has NULL octet(s) and `content-length` header is missing. + * + * ```javascript + * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"}); + * + * // Only destination is mandatory parameter + * client.publish({destination: "/queue/test", body: "Hello, STOMP"}); + * + * // Skip content-length header in the frame to the broker + * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true}); + * + * var binaryData = generateBinaryData(); // This need to be of type Uint8Array + * // setting content-type header is not mandatory, however a good practice + * client.publish({destination: '/topic/special', binaryBody: binaryData, + * headers: {'content-type': 'application/octet-stream'}}); + * ``` + */ + publish(params) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.publish(params); + } + _checkConnection() { + if (!this.connected) { + throw new TypeError('There is no underlying STOMP connection'); + } + } + /** + * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement. + * To request an acknowledgement, a `receipt` header needs to be sent with the actual request. + * The value (say receipt-id) for this header needs to be unique for each use. + * Typically, a sequence, a UUID, a random number or a combination may be used. + * + * A complaint broker will send a RECEIPT frame when an operation has actually been completed. + * The operation needs to be matched based on the value of the receipt-id. + * + * This method allows watching for a receipt and invoking the callback + * when the corresponding receipt has been received. + * + * The actual {@link IFrame} will be passed as parameter to the callback. + * + * Example: + * ```javascript + * // Subscribing with acknowledgement + * let receiptId = randomText(); + * + * client.watchForReceipt(receiptId, function() { + * // Will be called after server acknowledges + * }); + * + * client.subscribe(TEST.destination, onMessage, {receipt: receiptId}); + * + * + * // Publishing with acknowledgement + * receiptId = randomText(); + * + * client.watchForReceipt(receiptId, function() { + * // Will be called after server acknowledges + * }); + * client.publish({destination: TEST.destination, headers: {receipt: receiptId}, body: msg}); + * ``` + */ + watchForReceipt(receiptId, callback) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.watchForReceipt(receiptId, callback); + } + /** + * Subscribe to a STOMP Broker location. The callback will be invoked for each + * received message with the {@link IMessage} as argument. + * + * Note: The library will generate a unique ID if there is none provided in the headers. + * To use your own ID, pass it using the `headers` argument. + * + * ```javascript + * callback = function(message) { + * // called when the client receives a STOMP message from the server + * if (message.body) { + * alert("got message with body " + message.body) + * } else { + * alert("got empty message"); + * } + * }); + * + * var subscription = client.subscribe("/queue/test", callback); + * + * // Explicit subscription id + * var mySubId = 'my-subscription-id-001'; + * var subscription = client.subscribe(destination, callback, { id: mySubId }); + * ``` + */ + subscribe(destination, callback, headers = {}) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + return this._stompHandler.subscribe(destination, callback, headers); + } + /** + * It is preferable to unsubscribe from a subscription by calling + * `unsubscribe()` directly on {@link StompSubscription} returned by `client.subscribe()`: + * + * ```javascript + * var subscription = client.subscribe(destination, onmessage); + * // ... + * subscription.unsubscribe(); + * ``` + * + * See: https://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame + */ + unsubscribe(id, headers = {}) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.unsubscribe(id, headers); + } + /** + * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit} + * and [abort]{@link ITransaction#abort}. + * + * `transactionId` is optional, if not passed the library will generate it internally. + */ + begin(transactionId) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + return this._stompHandler.begin(transactionId); + } + /** + * Commit a transaction. + * + * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on + * {@link ITransaction} returned by [client.begin]{@link Client#begin}. + * + * ```javascript + * var tx = client.begin(txId); + * //... + * tx.commit(); + * ``` + */ + commit(transactionId) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.commit(transactionId); + } + /** + * Abort a transaction. + * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on + * {@link ITransaction} returned by [client.begin]{@link Client#begin}. + * + * ```javascript + * var tx = client.begin(txId); + * //... + * tx.abort(); + * ``` + */ + abort(transactionId) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.abort(transactionId); + } + /** + * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly + * on the {@link IMessage} handled by a subscription callback: + * + * ```javascript + * var callback = function (message) { + * // process the message + * // acknowledge it + * message.ack(); + * }; + * client.subscribe(destination, callback, {'ack': 'client'}); + * ``` + */ + ack(messageId, subscriptionId, headers = {}) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.ack(messageId, subscriptionId, headers); + } + /** + * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly + * on the {@link IMessage} handled by a subscription callback: + * + * ```javascript + * var callback = function (message) { + * // process the message + * // an error occurs, nack it + * message.nack(); + * }; + * client.subscribe(destination, callback, {'ack': 'client'}); + * ``` + */ + nack(messageId, subscriptionId, headers = {}) { + this._checkConnection(); + // @ts-ignore - we already checked that there is a _stompHandler, and it is connected + this._stompHandler.nack(messageId, subscriptionId, headers); + } + } - /** - * The STOMP protocol handler - * - * Part of `@stomp/stompjs`. - * - * @internal - */ - class StompHandler { - constructor(_client, _webSocket, config) { - this._client = _client; - this._webSocket = _webSocket; - this._connected = false; - this._serverFrameHandlers = { - // [CONNECTED Frame](https://stomp.github.com/stomp-specification-1.2.html#CONNECTED_Frame) - CONNECTED: frame => { - this.debug(`connected to server ${frame.headers.server}`); - this._connected = true; - this._connectedVersion = frame.headers.version; - // STOMP version 1.2 needs header values to be escaped - if (this._connectedVersion === Versions.V1_2) { - this._escapeHeaderValues = true; - } - this._setupHeartbeat(frame.headers); - this.onConnect(frame); - }, - // [MESSAGE Frame](https://stomp.github.com/stomp-specification-1.2.html#MESSAGE) - MESSAGE: frame => { - // the callback is registered when the client calls - // `subscribe()`. - // If there is no registered subscription for the received message, - // the default `onUnhandledMessage` callback is used that the client can set. - // This is useful for subscriptions that are automatically created - // on the browser side (e.g. [RabbitMQ's temporary - // queues](https://www.rabbitmq.com/stomp.html)). - const subscription = frame.headers.subscription; - const onReceive = this._subscriptions[subscription] || this.onUnhandledMessage; - // bless the frame to be a Message - const message = frame; - const client = this; - const messageId = this._connectedVersion === Versions.V1_2 - ? message.headers.ack - : message.headers['message-id']; - // add `ack()` and `nack()` methods directly to the returned frame - // so that a simple call to `message.ack()` can acknowledge the message. - message.ack = (headers = {}) => { - return client.ack(messageId, subscription, headers); - }; - message.nack = (headers = {}) => { - return client.nack(messageId, subscription, headers); - }; - onReceive(message); - }, - // [RECEIPT Frame](https://stomp.github.com/stomp-specification-1.2.html#RECEIPT) - RECEIPT: frame => { - const callback = this._receiptWatchers[frame.headers['receipt-id']]; - if (callback) { - callback(frame); - // Server will acknowledge only once, remove the callback - delete this._receiptWatchers[frame.headers['receipt-id']]; - } - else { - this.onUnhandledReceipt(frame); - } - }, - // [ERROR Frame](https://stomp.github.com/stomp-specification-1.2.html#ERROR) - ERROR: frame => { - this.onStompError(frame); - }, - }; - // used to index subscribers - this._counter = 0; - // subscription callbacks indexed by subscriber's ID - this._subscriptions = {}; - // receipt-watchers indexed by receipts-ids - this._receiptWatchers = {}; - this._partialData = ''; - this._escapeHeaderValues = false; - this._lastServerActivityTS = Date.now(); - this.debug = config.debug; - this.stompVersions = config.stompVersions; - this.connectHeaders = config.connectHeaders; - this.disconnectHeaders = config.disconnectHeaders; - this.heartbeatIncoming = config.heartbeatIncoming; - this.heartbeatOutgoing = config.heartbeatOutgoing; - this.splitLargeFrames = config.splitLargeFrames; - this.maxWebSocketChunkSize = config.maxWebSocketChunkSize; - this.forceBinaryWSFrames = config.forceBinaryWSFrames; - this.logRawCommunication = config.logRawCommunication; - this.appendMissingNULLonIncoming = config.appendMissingNULLonIncoming; - this.discardWebsocketOnCommFailure = config.discardWebsocketOnCommFailure; - this.onConnect = config.onConnect; - this.onDisconnect = config.onDisconnect; - this.onStompError = config.onStompError; - this.onWebSocketClose = config.onWebSocketClose; - this.onWebSocketError = config.onWebSocketError; - this.onUnhandledMessage = config.onUnhandledMessage; - this.onUnhandledReceipt = config.onUnhandledReceipt; - this.onUnhandledFrame = config.onUnhandledFrame; - } - get connectedVersion() { - return this._connectedVersion; - } - get connected() { - return this._connected; - } - start() { - const parser = new Parser( - // On Frame - rawFrame => { - const frame = FrameImpl.fromRawFrame(rawFrame, this._escapeHeaderValues); - // if this.logRawCommunication is set, the rawChunk is logged at this._webSocket.onmessage - if (!this.logRawCommunication) { - this.debug(`<<< ${frame}`); - } - const serverFrameHandler = this._serverFrameHandlers[frame.command] || this.onUnhandledFrame; - serverFrameHandler(frame); - }, - // On Incoming Ping - () => { - this.debug('<<< PONG'); - }); - this._webSocket.onmessage = (evt) => { - this.debug('Received data'); - this._lastServerActivityTS = Date.now(); - if (this.logRawCommunication) { - const rawChunkAsString = evt.data instanceof ArrayBuffer - ? new TextDecoder().decode(evt.data) - : evt.data; - this.debug(`<<< ${rawChunkAsString}`); - } - parser.parseChunk(evt.data, this.appendMissingNULLonIncoming); - }; - this._webSocket.onclose = (closeEvent) => { - this.debug(`Connection closed to ${this._webSocket.url}`); - this._cleanUp(); - this.onWebSocketClose(closeEvent); - }; - this._webSocket.onerror = (errorEvent) => { - this.onWebSocketError(errorEvent); - }; - this._webSocket.onopen = () => { - // Clone before updating - const connectHeaders = Object.assign({}, this.connectHeaders); - this.debug('Web Socket Opened...'); - connectHeaders['accept-version'] = this.stompVersions.supportedVersions(); - connectHeaders['heart-beat'] = [ - this.heartbeatOutgoing, - this.heartbeatIncoming, - ].join(','); - this._transmit({ command: 'CONNECT', headers: connectHeaders }); - }; - } - _setupHeartbeat(headers) { - if (headers.version !== Versions.V1_1 && - headers.version !== Versions.V1_2) { - return; - } - // It is valid for the server to not send this header - // https://stomp.github.io/stomp-specification-1.2.html#Heart-beating - if (!headers['heart-beat']) { - return; - } - // heart-beat header received from the server looks like: - // - // heart-beat: sx, sy - const [serverOutgoing, serverIncoming] = headers['heart-beat'] - .split(',') - .map((v) => parseInt(v, 10)); - if (this.heartbeatOutgoing !== 0 && serverIncoming !== 0) { - const ttl = Math.max(this.heartbeatOutgoing, serverIncoming); - this.debug(`send PING every ${ttl}ms`); - this._pinger = setInterval(() => { - if (this._webSocket.readyState === exports.StompSocketState.OPEN) { - this._webSocket.send(BYTE.LF); - this.debug('>>> PING'); - } - }, ttl); - } - if (this.heartbeatIncoming !== 0 && serverOutgoing !== 0) { - const ttl = Math.max(this.heartbeatIncoming, serverOutgoing); - this.debug(`check PONG every ${ttl}ms`); - this._ponger = setInterval(() => { - const delta = Date.now() - this._lastServerActivityTS; - // We wait twice the TTL to be flexible on window's setInterval calls - if (delta > ttl * 2) { - this.debug(`did not receive server activity for the last ${delta}ms`); - this._closeOrDiscardWebsocket(); - } - }, ttl); - } - } - _closeOrDiscardWebsocket() { - if (this.discardWebsocketOnCommFailure) { - this.debug('Discarding websocket, the underlying socket may linger for a while'); - this.discardWebsocket(); - } - else { - this.debug('Issuing close on the websocket'); - this._closeWebsocket(); - } - } - forceDisconnect() { - if (this._webSocket) { - if (this._webSocket.readyState === exports.StompSocketState.CONNECTING || - this._webSocket.readyState === exports.StompSocketState.OPEN) { - this._closeOrDiscardWebsocket(); - } - } - } - _closeWebsocket() { - this._webSocket.onmessage = () => { }; // ignore messages - this._webSocket.close(); - } - discardWebsocket() { - if (typeof this._webSocket.terminate !== 'function') { - augmentWebsocket(this._webSocket, (msg) => this.debug(msg)); - } - // @ts-ignore - this method will be there at this stage - this._webSocket.terminate(); - } - _transmit(params) { - const { command, headers, body, binaryBody, skipContentLengthHeader } = params; - const frame = new FrameImpl({ - command, - headers, - body, - binaryBody, - escapeHeaderValues: this._escapeHeaderValues, - skipContentLengthHeader, - }); - let rawChunk = frame.serialize(); - if (this.logRawCommunication) { - this.debug(`>>> ${rawChunk}`); - } - else { - this.debug(`>>> ${frame}`); - } - if (this.forceBinaryWSFrames && typeof rawChunk === 'string') { - rawChunk = new TextEncoder().encode(rawChunk); - } - if (typeof rawChunk !== 'string' || !this.splitLargeFrames) { - this._webSocket.send(rawChunk); - } - else { - let out = rawChunk; - while (out.length > 0) { - const chunk = out.substring(0, this.maxWebSocketChunkSize); - out = out.substring(this.maxWebSocketChunkSize); - this._webSocket.send(chunk); - this.debug(`chunk sent = ${chunk.length}, remaining = ${out.length}`); - } - } - } - dispose() { - if (this.connected) { - try { - // clone before updating - const disconnectHeaders = Object.assign({}, this.disconnectHeaders); - if (!disconnectHeaders.receipt) { - disconnectHeaders.receipt = `close-${this._counter++}`; - } - this.watchForReceipt(disconnectHeaders.receipt, frame => { - this._closeWebsocket(); - this._cleanUp(); - this.onDisconnect(frame); - }); - this._transmit({ command: 'DISCONNECT', headers: disconnectHeaders }); - } - catch (error) { - this.debug(`Ignoring error during disconnect ${error}`); - } - } - else { - if (this._webSocket.readyState === exports.StompSocketState.CONNECTING || - this._webSocket.readyState === exports.StompSocketState.OPEN) { - this._closeWebsocket(); - } - } - } - _cleanUp() { - this._connected = false; - if (this._pinger) { - clearInterval(this._pinger); - this._pinger = undefined; - } - if (this._ponger) { - clearInterval(this._ponger); - this._ponger = undefined; - } - } - publish(params) { - const { destination, headers, body, binaryBody, skipContentLengthHeader } = params; - const hdrs = Object.assign({ destination }, headers); - this._transmit({ - command: 'SEND', - headers: hdrs, - body, - binaryBody, - skipContentLengthHeader, - }); - } - watchForReceipt(receiptId, callback) { - this._receiptWatchers[receiptId] = callback; - } - subscribe(destination, callback, headers = {}) { - headers = Object.assign({}, headers); - if (!headers.id) { - headers.id = `sub-${this._counter++}`; - } - headers.destination = destination; - this._subscriptions[headers.id] = callback; - this._transmit({ command: 'SUBSCRIBE', headers }); - const client = this; - return { - id: headers.id, - unsubscribe(hdrs) { - return client.unsubscribe(headers.id, hdrs); - }, - }; - } - unsubscribe(id, headers = {}) { - headers = Object.assign({}, headers); - delete this._subscriptions[id]; - headers.id = id; - this._transmit({ command: 'UNSUBSCRIBE', headers }); - } - begin(transactionId) { - const txId = transactionId || `tx-${this._counter++}`; - this._transmit({ - command: 'BEGIN', - headers: { - transaction: txId, - }, - }); - const client = this; - return { - id: txId, - commit() { - client.commit(txId); - }, - abort() { - client.abort(txId); - }, - }; - } - commit(transactionId) { - this._transmit({ - command: 'COMMIT', - headers: { - transaction: transactionId, - }, - }); - } - abort(transactionId) { - this._transmit({ - command: 'ABORT', - headers: { - transaction: transactionId, - }, - }); - } - ack(messageId, subscriptionId, headers = {}) { - headers = Object.assign({}, headers); - if (this._connectedVersion === Versions.V1_2) { - headers.id = messageId; - } - else { - headers['message-id'] = messageId; - } - headers.subscription = subscriptionId; - this._transmit({ command: 'ACK', headers }); - } - nack(messageId, subscriptionId, headers = {}) { - headers = Object.assign({}, headers); - if (this._connectedVersion === Versions.V1_2) { - headers.id = messageId; - } - else { - headers['message-id'] = messageId; - } - headers.subscription = subscriptionId; - return this._transmit({ command: 'NACK', headers }); - } - } + /** + * Configuration options for STOMP Client, each key corresponds to + * field by the same name in {@link Client}. This can be passed to + * the constructor of {@link Client} or to [Client#configure]{@link Client#configure}. + * + * Part of `@stomp/stompjs`. + */ + class StompConfig { + } - /** - * STOMP Client Class. - * - * Part of `@stomp/stompjs`. - */ - class Client { - /** - * Create an instance. - */ - constructor(conf = {}) { - /** - * STOMP versions to attempt during STOMP handshake. By default, versions `1.2`, `1.1`, and `1.0` are attempted. - * - * Example: - * ```javascript - * // Try only versions 1.1 and 1.0 - * client.stompVersions = new Versions(['1.1', '1.0']) - * ``` - */ - this.stompVersions = Versions.default; - /** - * Will retry if Stomp connection is not established in specified milliseconds. - * Default 0, which switches off automatic reconnection. - */ - this.connectionTimeout = 0; - /** - * automatically reconnect with delay in milliseconds, set to 0 to disable. - */ - this.reconnectDelay = 5000; - /** - * Incoming heartbeat interval in milliseconds. Set to 0 to disable. - */ - this.heartbeatIncoming = 10000; - /** - * Outgoing heartbeat interval in milliseconds. Set to 0 to disable. - */ - this.heartbeatOutgoing = 10000; - /** - * This switches on a non-standard behavior while sending WebSocket packets. - * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}. - * Only Java Spring brokers seem to support this mode. - * - * WebSockets, by itself, split large (text) packets, - * so it is not needed with a truly compliant STOMP/WebSocket broker. - * Setting it for such a broker will cause large messages to fail. - * - * `false` by default. - * - * Binary frames are never split. - */ - this.splitLargeFrames = false; - /** - * See [splitLargeFrames]{@link Client#splitLargeFrames}. - * This has no effect if [splitLargeFrames]{@link Client#splitLargeFrames} is `false`. - */ - this.maxWebSocketChunkSize = 8 * 1024; - /** - * Usually the - * [type of WebSocket frame]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send#Parameters} - * is automatically decided by type of the payload. - * Default is `false`, which should work with all compliant brokers. - * - * Set this flag to force binary frames. - */ - this.forceBinaryWSFrames = false; - /** - * A bug in ReactNative chops a string on occurrence of a NULL. - * See issue [https://github.com/stomp-js/stompjs/issues/89]{@link https://github.com/stomp-js/stompjs/issues/89}. - * This makes incoming WebSocket messages invalid STOMP packets. - * Setting this flag attempts to reverse the damage by appending a NULL. - * If the broker splits a large message into multiple WebSocket messages, - * this flag will cause data loss and abnormal termination of connection. - * - * This is not an ideal solution, but a stop gap until the underlying issue is fixed at ReactNative library. - */ - this.appendMissingNULLonIncoming = false; - /** - * Browsers do not immediately close WebSockets when `.close` is issued. - * This may cause reconnection to take a significantly long time in case - * of some types of failures. - * In case of incoming heartbeat failure, this experimental flag instructs - * the library to discard the socket immediately - * (even before it is actually closed). - */ - this.discardWebsocketOnCommFailure = false; - /** - * Activation state. - * - * It will usually be ACTIVE or INACTIVE. - * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING. - */ - this.state = exports.ActivationState.INACTIVE; - // No op callbacks - const noOp = () => { }; - this.debug = noOp; - this.beforeConnect = noOp; - this.onConnect = noOp; - this.onDisconnect = noOp; - this.onUnhandledMessage = noOp; - this.onUnhandledReceipt = noOp; - this.onUnhandledFrame = noOp; - this.onStompError = noOp; - this.onWebSocketClose = noOp; - this.onWebSocketError = noOp; - this.logRawCommunication = false; - this.onChangeState = noOp; - // These parameters would typically get proper values before connect is called - this.connectHeaders = {}; - this._disconnectHeaders = {}; - // Apply configuration - this.configure(conf); - } - /** - * Underlying WebSocket instance, READONLY. - */ - get webSocket() { - return this._stompHandler?._webSocket; - } - /** - * Disconnection headers. - */ - get disconnectHeaders() { - return this._disconnectHeaders; - } - set disconnectHeaders(value) { - this._disconnectHeaders = value; - if (this._stompHandler) { - this._stompHandler.disconnectHeaders = this._disconnectHeaders; - } - } - /** - * `true` if there is an active connection to STOMP Broker - */ - get connected() { - return !!this._stompHandler && this._stompHandler.connected; - } - /** - * version of STOMP protocol negotiated with the server, READONLY - */ - get connectedVersion() { - return this._stompHandler ? this._stompHandler.connectedVersion : undefined; - } - /** - * if the client is active (connected or going to reconnect) - */ - get active() { - return this.state === exports.ActivationState.ACTIVE; - } - _changeState(state) { - this.state = state; - this.onChangeState(state); - } - /** - * Update configuration. - */ - configure(conf) { - // bulk assign all properties to this - Object.assign(this, conf); - } - /** - * Initiate the connection with the broker. - * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay}, - * it will keep trying to reconnect. - * - * Call [Client#deactivate]{@link Client#deactivate} to disconnect and stop reconnection attempts. - */ - activate() { - const _activate = () => { - if (this.active) { - this.debug('Already ACTIVE, ignoring request to activate'); - return; - } - this._changeState(exports.ActivationState.ACTIVE); - this._connect(); - }; - // if it is deactivating, wait for it to complete before activating. - if (this.state === exports.ActivationState.DEACTIVATING) { - this.debug('Waiting for deactivation to finish before activating'); - this.deactivate().then(() => { - _activate(); - }); - } - else { - _activate(); - } - } - async _connect() { - await this.beforeConnect(); - if (this._stompHandler) { - this.debug('There is already a stompHandler, skipping the call to connect'); - return; - } - if (!this.active) { - this.debug('Client has been marked inactive, will not attempt to connect'); - return; - } - // setup connection watcher - if (this.connectionTimeout > 0) { - // clear first - if (this._connectionWatcher) { - clearTimeout(this._connectionWatcher); - } - this._connectionWatcher = setTimeout(() => { - if (this.connected) { - return; - } - // Connection not established, close the underlying socket - // a reconnection will be attempted - this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`); - this.forceDisconnect(); - }, this.connectionTimeout); - } - this.debug('Opening Web Socket...'); - // Get the actual WebSocket (or a similar object) - const webSocket = this._createWebSocket(); - this._stompHandler = new StompHandler(this, webSocket, { - debug: this.debug, - stompVersions: this.stompVersions, - connectHeaders: this.connectHeaders, - disconnectHeaders: this._disconnectHeaders, - heartbeatIncoming: this.heartbeatIncoming, - heartbeatOutgoing: this.heartbeatOutgoing, - splitLargeFrames: this.splitLargeFrames, - maxWebSocketChunkSize: this.maxWebSocketChunkSize, - forceBinaryWSFrames: this.forceBinaryWSFrames, - logRawCommunication: this.logRawCommunication, - appendMissingNULLonIncoming: this.appendMissingNULLonIncoming, - discardWebsocketOnCommFailure: this.discardWebsocketOnCommFailure, - onConnect: frame => { - // Successfully connected, stop the connection watcher - if (this._connectionWatcher) { - clearTimeout(this._connectionWatcher); - this._connectionWatcher = undefined; - } - if (!this.active) { - this.debug('STOMP got connected while deactivate was issued, will disconnect now'); - this._disposeStompHandler(); - return; - } - this.onConnect(frame); - }, - onDisconnect: frame => { - this.onDisconnect(frame); - }, - onStompError: frame => { - this.onStompError(frame); - }, - onWebSocketClose: evt => { - this._stompHandler = undefined; // a new one will be created in case of a reconnect - if (this.state === exports.ActivationState.DEACTIVATING) { - // Mark deactivation complete - this._changeState(exports.ActivationState.INACTIVE); - } - // The callback is called before attempting to reconnect, this would allow the client - // to be `deactivated` in the callback. - this.onWebSocketClose(evt); - if (this.active) { - this._schedule_reconnect(); - } - }, - onWebSocketError: evt => { - this.onWebSocketError(evt); - }, - onUnhandledMessage: message => { - this.onUnhandledMessage(message); - }, - onUnhandledReceipt: frame => { - this.onUnhandledReceipt(frame); - }, - onUnhandledFrame: frame => { - this.onUnhandledFrame(frame); - }, - }); - this._stompHandler.start(); - } - _createWebSocket() { - let webSocket; - if (this.webSocketFactory) { - webSocket = this.webSocketFactory(); - } - else if (this.brokerURL) { - webSocket = new WebSocket(this.brokerURL, this.stompVersions.protocolVersions()); - } - else { - throw new Error('Either brokerURL or webSocketFactory must be provided'); - } - webSocket.binaryType = 'arraybuffer'; - return webSocket; - } - _schedule_reconnect() { - if (this.reconnectDelay > 0) { - this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`); - this._reconnector = setTimeout(() => { - this._connect(); - }, this.reconnectDelay); - } - } - /** - * Disconnect if connected and stop auto reconnect loop. - * Appropriate callbacks will be invoked if there is an underlying STOMP connection. - * - * This call is async. It will resolve immediately if there is no underlying active websocket, - * otherwise, it will resolve after the underlying websocket is properly disposed of. - * - * It is not an error to invoke this method more than once. - * Each of those would resolve on completion of deactivation. - * - * To reactivate, you can call [Client#activate]{@link Client#activate}. - * - * Experimental: pass `force: true` to immediately discard the underlying connection. - * This mode will skip both the STOMP and the Websocket shutdown sequences. - * In some cases, browsers take a long time in the Websocket shutdown - * if the underlying connection had gone stale. - * Using this mode can speed up. - * When this mode is used, the actual Websocket may linger for a while - * and the broker may not realize that the connection is no longer in use. - * - * It is possible to invoke this method initially without the `force` option - * and subsequently, say after a wait, with the `force` option. - */ - async deactivate(options = {}) { - const force = options.force || false; - const needToDispose = this.active; - let retPromise; - if (this.state === exports.ActivationState.INACTIVE) { - this.debug(`Already INACTIVE, nothing more to do`); - return Promise.resolve(); - } - this._changeState(exports.ActivationState.DEACTIVATING); - // Clear if a reconnection was scheduled - if (this._reconnector) { - clearTimeout(this._reconnector); - this._reconnector = undefined; - } - if (this._stompHandler && - // @ts-ignore - if there is a _stompHandler, there is the webSocket - this.webSocket.readyState !== exports.StompSocketState.CLOSED) { - const origOnWebSocketClose = this._stompHandler.onWebSocketClose; - // we need to wait for the underlying websocket to close - retPromise = new Promise((resolve, reject) => { - // @ts-ignore - there is a _stompHandler - this._stompHandler.onWebSocketClose = evt => { - origOnWebSocketClose(evt); - resolve(); - }; - }); - } - else { - // indicate that auto reconnect loop should terminate - this._changeState(exports.ActivationState.INACTIVE); - return Promise.resolve(); - } - if (force) { - this._stompHandler?.discardWebsocket(); - } - else if (needToDispose) { - this._disposeStompHandler(); - } - return retPromise; - } - /** - * Force disconnect if there is an active connection by directly closing the underlying WebSocket. - * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker. - * After forcing disconnect, automatic reconnect will be attempted. - * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well. - */ - forceDisconnect() { - if (this._stompHandler) { - this._stompHandler.forceDisconnect(); - } - } - _disposeStompHandler() { - // Dispose STOMP Handler - if (this._stompHandler) { - this._stompHandler.dispose(); - } - } - /** - * Send a message to a named destination. Refer to your STOMP broker documentation for types - * and naming of destinations. - * - * STOMP protocol specifies and suggests some headers and also allows broker-specific headers. - * - * `body` must be String. - * You will need to covert the payload to string in case it is not string (e.g. JSON). - * - * To send a binary message body, use `binaryBody` parameter. It should be a - * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). - * Sometimes brokers may not support binary frames out of the box. - * Please check your broker documentation. - * - * `content-length` header is automatically added to the STOMP Frame sent to the broker. - * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added. - * For binary messages, `content-length` header is always added. - * - * Caution: The broker will, most likely, report an error and disconnect - * if the message body has NULL octet(s) and `content-length` header is missing. - * - * ```javascript - * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"}); - * - * // Only destination is mandatory parameter - * client.publish({destination: "/queue/test", body: "Hello, STOMP"}); - * - * // Skip content-length header in the frame to the broker - * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true}); - * - * var binaryData = generateBinaryData(); // This need to be of type Uint8Array - * // setting content-type header is not mandatory, however a good practice - * client.publish({destination: '/topic/special', binaryBody: binaryData, - * headers: {'content-type': 'application/octet-stream'}}); - * ``` - */ - publish(params) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.publish(params); - } - _checkConnection() { - if (!this.connected) { - throw new TypeError('There is no underlying STOMP connection'); - } - } - /** - * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement. - * To request an acknowledgement, a `receipt` header needs to be sent with the actual request. - * The value (say receipt-id) for this header needs to be unique for each use. - * Typically, a sequence, a UUID, a random number or a combination may be used. - * - * A complaint broker will send a RECEIPT frame when an operation has actually been completed. - * The operation needs to be matched based on the value of the receipt-id. - * - * This method allows watching for a receipt and invoking the callback - * when the corresponding receipt has been received. - * - * The actual {@link IFrame} will be passed as parameter to the callback. - * - * Example: - * ```javascript - * // Subscribing with acknowledgement - * let receiptId = randomText(); - * - * client.watchForReceipt(receiptId, function() { - * // Will be called after server acknowledges - * }); - * - * client.subscribe(TEST.destination, onMessage, {receipt: receiptId}); - * - * - * // Publishing with acknowledgement - * receiptId = randomText(); - * - * client.watchForReceipt(receiptId, function() { - * // Will be called after server acknowledges - * }); - * client.publish({destination: TEST.destination, headers: {receipt: receiptId}, body: msg}); - * ``` - */ - watchForReceipt(receiptId, callback) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.watchForReceipt(receiptId, callback); - } - /** - * Subscribe to a STOMP Broker location. The callback will be invoked for each - * received message with the {@link IMessage} as argument. - * - * Note: The library will generate a unique ID if there is none provided in the headers. - * To use your own ID, pass it using the `headers` argument. - * - * ```javascript - * callback = function(message) { - * // called when the client receives a STOMP message from the server - * if (message.body) { - * alert("got message with body " + message.body) - * } else { - * alert("got empty message"); - * } - * }); - * - * var subscription = client.subscribe("/queue/test", callback); - * - * // Explicit subscription id - * var mySubId = 'my-subscription-id-001'; - * var subscription = client.subscribe(destination, callback, { id: mySubId }); - * ``` - */ - subscribe(destination, callback, headers = {}) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - return this._stompHandler.subscribe(destination, callback, headers); - } - /** - * It is preferable to unsubscribe from a subscription by calling - * `unsubscribe()` directly on {@link StompSubscription} returned by `client.subscribe()`: - * - * ```javascript - * var subscription = client.subscribe(destination, onmessage); - * // ... - * subscription.unsubscribe(); - * ``` - * - * See: https://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame - */ - unsubscribe(id, headers = {}) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.unsubscribe(id, headers); - } - /** - * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit} - * and [abort]{@link ITransaction#abort}. - * - * `transactionId` is optional, if not passed the library will generate it internally. - */ - begin(transactionId) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - return this._stompHandler.begin(transactionId); - } - /** - * Commit a transaction. - * - * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on - * {@link ITransaction} returned by [client.begin]{@link Client#begin}. - * - * ```javascript - * var tx = client.begin(txId); - * //... - * tx.commit(); - * ``` - */ - commit(transactionId) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.commit(transactionId); - } - /** - * Abort a transaction. - * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on - * {@link ITransaction} returned by [client.begin]{@link Client#begin}. - * - * ```javascript - * var tx = client.begin(txId); - * //... - * tx.abort(); - * ``` - */ - abort(transactionId) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.abort(transactionId); - } - /** - * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly - * on the {@link IMessage} handled by a subscription callback: - * - * ```javascript - * var callback = function (message) { - * // process the message - * // acknowledge it - * message.ack(); - * }; - * client.subscribe(destination, callback, {'ack': 'client'}); - * ``` - */ - ack(messageId, subscriptionId, headers = {}) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.ack(messageId, subscriptionId, headers); - } - /** - * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly - * on the {@link IMessage} handled by a subscription callback: - * - * ```javascript - * var callback = function (message) { - * // process the message - * // an error occurs, nack it - * message.nack(); - * }; - * client.subscribe(destination, callback, {'ack': 'client'}); - * ``` - */ - nack(messageId, subscriptionId, headers = {}) { - this._checkConnection(); - // @ts-ignore - we already checked that there is a _stompHandler, and it is connected - this._stompHandler.nack(messageId, subscriptionId, headers); - } - } + /** + * STOMP headers. Many functions calls will accept headers as parameters. + * The headers sent by Broker will be available as [IFrame#headers]{@link IFrame#headers}. + * + * `key` and `value` must be valid strings. + * In addition, `key` must not contain `CR`, `LF`, or `:`. + * + * Part of `@stomp/stompjs`. + */ + class StompHeaders { + } - /** - * Configuration options for STOMP Client, each key corresponds to - * field by the same name in {@link Client}. This can be passed to - * the constructor of {@link Client} or to [Client#configure]{@link Client#configure}. - * - * Part of `@stomp/stompjs`. - */ - class StompConfig { - } + /** + * Part of `@stomp/stompjs`. + * + * @internal + */ + class HeartbeatInfo { + constructor(client) { + this.client = client; + } + get outgoing() { + return this.client.heartbeatOutgoing; + } + set outgoing(value) { + this.client.heartbeatOutgoing = value; + } + get incoming() { + return this.client.heartbeatIncoming; + } + set incoming(value) { + this.client.heartbeatIncoming = value; + } + } - /** - * STOMP headers. Many functions calls will accept headers as parameters. - * The headers sent by Broker will be available as [IFrame#headers]{@link IFrame#headers}. - * - * `key` and `value` must be valid strings. - * In addition, `key` must not contain `CR`, `LF`, or `:`. - * - * Part of `@stomp/stompjs`. - */ - class StompHeaders { - } + /** + * Available for backward compatibility, please shift to using {@link Client}. + * + * **Deprecated** + * + * Part of `@stomp/stompjs`. + * + * To upgrade, please follow the [Upgrade Guide](https://stomp-js.github.io/guide/stompjs/upgrading-stompjs.html) + */ + class CompatClient extends Client { + /** + * Available for backward compatibility, please shift to using {@link Client} + * and [Client#webSocketFactory]{@link Client#webSocketFactory}. + * + * **Deprecated** + * + * @internal + */ + constructor(webSocketFactory) { + super(); + /** + * It is no op now. No longer needed. Large packets work out of the box. + */ + this.maxWebSocketFrameSize = 16 * 1024; + this._heartbeatInfo = new HeartbeatInfo(this); + this.reconnect_delay = 0; + this.webSocketFactory = webSocketFactory; + // Default from previous version + this.debug = (...message) => { + console.log(...message); + }; + } + _parseConnect(...args) { + let closeEventCallback; + let connectCallback; + let errorCallback; + let headers = {}; + if (args.length < 2) { + throw new Error('Connect requires at least 2 arguments'); + } + if (typeof args[1] === 'function') { + [headers, connectCallback, errorCallback, closeEventCallback] = args; + } + else { + switch (args.length) { + case 6: + [ + headers.login, + headers.passcode, + connectCallback, + errorCallback, + closeEventCallback, + headers.host, + ] = args; + break; + default: + [ + headers.login, + headers.passcode, + connectCallback, + errorCallback, + closeEventCallback, + ] = args; + } + } + return [headers, connectCallback, errorCallback, closeEventCallback]; + } + /** + * Available for backward compatibility, please shift to using [Client#activate]{@link Client#activate}. + * + * **Deprecated** + * + * The `connect` method accepts different number of arguments and types. See the Overloads list. Use the + * version with headers to pass your broker specific options. + * + * overloads: + * - connect(headers, connectCallback) + * - connect(headers, connectCallback, errorCallback) + * - connect(login, passcode, connectCallback) + * - connect(login, passcode, connectCallback, errorCallback) + * - connect(login, passcode, connectCallback, errorCallback, closeEventCallback) + * - connect(login, passcode, connectCallback, errorCallback, closeEventCallback, host) + * + * params: + * - headers, see [Client#connectHeaders]{@link Client#connectHeaders} + * - connectCallback, see [Client#onConnect]{@link Client#onConnect} + * - errorCallback, see [Client#onStompError]{@link Client#onStompError} + * - closeEventCallback, see [Client#onWebSocketClose]{@link Client#onWebSocketClose} + * - login [String], see [Client#connectHeaders](../classes/Client.html#connectHeaders) + * - passcode [String], [Client#connectHeaders](../classes/Client.html#connectHeaders) + * - host [String], see [Client#connectHeaders](../classes/Client.html#connectHeaders) + * + * To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html) + */ + connect(...args) { + const out = this._parseConnect(...args); + if (out[0]) { + this.connectHeaders = out[0]; + } + if (out[1]) { + this.onConnect = out[1]; + } + if (out[2]) { + this.onStompError = out[2]; + } + if (out[3]) { + this.onWebSocketClose = out[3]; + } + super.activate(); + } + /** + * Available for backward compatibility, please shift to using [Client#deactivate]{@link Client#deactivate}. + * + * **Deprecated** + * + * See: + * [Client#onDisconnect]{@link Client#onDisconnect}, and + * [Client#disconnectHeaders]{@link Client#disconnectHeaders} + * + * To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html) + */ + disconnect(disconnectCallback, headers = {}) { + if (disconnectCallback) { + this.onDisconnect = disconnectCallback; + } + this.disconnectHeaders = headers; + super.deactivate(); + } + /** + * Available for backward compatibility, use [Client#publish]{@link Client#publish}. + * + * Send a message to a named destination. Refer to your STOMP broker documentation for types + * and naming of destinations. The headers will, typically, be available to the subscriber. + * However, there may be special purpose headers corresponding to your STOMP broker. + * + * **Deprecated**, use [Client#publish]{@link Client#publish} + * + * Note: Body must be String. You will need to covert the payload to string in case it is not string (e.g. JSON) + * + * ```javascript + * client.send("/queue/test", {priority: 9}, "Hello, STOMP"); + * + * // If you want to send a message with a body, you must also pass the headers argument. + * client.send("/queue/test", {}, "Hello, STOMP"); + * ``` + * + * To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html) + */ + send(destination, headers = {}, body = '') { + headers = Object.assign({}, headers); + const skipContentLengthHeader = headers['content-length'] === false; + if (skipContentLengthHeader) { + delete headers['content-length']; + } + this.publish({ + destination, + headers: headers, + body, + skipContentLengthHeader, + }); + } + /** + * Available for backward compatibility, renamed to [Client#reconnectDelay]{@link Client#reconnectDelay}. + * + * **Deprecated** + */ + set reconnect_delay(value) { + this.reconnectDelay = value; + } + /** + * Available for backward compatibility, renamed to [Client#webSocket]{@link Client#webSocket}. + * + * **Deprecated** + */ + get ws() { + return this.webSocket; + } + /** + * Available for backward compatibility, renamed to [Client#connectedVersion]{@link Client#connectedVersion}. + * + * **Deprecated** + */ + get version() { + return this.connectedVersion; + } + /** + * Available for backward compatibility, renamed to [Client#onUnhandledMessage]{@link Client#onUnhandledMessage}. + * + * **Deprecated** + */ + get onreceive() { + return this.onUnhandledMessage; + } + /** + * Available for backward compatibility, renamed to [Client#onUnhandledMessage]{@link Client#onUnhandledMessage}. + * + * **Deprecated** + */ + set onreceive(value) { + this.onUnhandledMessage = value; + } + /** + * Available for backward compatibility, renamed to [Client#onUnhandledReceipt]{@link Client#onUnhandledReceipt}. + * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. + * + * **Deprecated** + */ + get onreceipt() { + return this.onUnhandledReceipt; + } + /** + * Available for backward compatibility, renamed to [Client#onUnhandledReceipt]{@link Client#onUnhandledReceipt}. + * + * **Deprecated** + */ + set onreceipt(value) { + this.onUnhandledReceipt = value; + } + /** + * Available for backward compatibility, renamed to [Client#heartbeatIncoming]{@link Client#heartbeatIncoming} + * [Client#heartbeatOutgoing]{@link Client#heartbeatOutgoing}. + * + * **Deprecated** + */ + get heartbeat() { + return this._heartbeatInfo; + } + /** + * Available for backward compatibility, renamed to [Client#heartbeatIncoming]{@link Client#heartbeatIncoming} + * [Client#heartbeatOutgoing]{@link Client#heartbeatOutgoing}. + * + * **Deprecated** + */ + set heartbeat(value) { + this.heartbeatIncoming = value.incoming; + this.heartbeatOutgoing = value.outgoing; + } + } - /** - * Part of `@stomp/stompjs`. - * - * @internal - */ - class HeartbeatInfo { - constructor(client) { - this.client = client; - } - get outgoing() { - return this.client.heartbeatOutgoing; - } - set outgoing(value) { - this.client.heartbeatOutgoing = value; - } - get incoming() { - return this.client.heartbeatIncoming; - } - set incoming(value) { - this.client.heartbeatIncoming = value; - } - } + /** + * STOMP Class, acts like a factory to create {@link Client}. + * + * Part of `@stomp/stompjs`. + * + * **Deprecated** + * + * It will be removed in next major version. Please switch to {@link Client}. + */ + class Stomp { + /** + * This method creates a WebSocket client that is connected to + * the STOMP server located at the url. + * + * ```javascript + * var url = "ws://localhost:61614/stomp"; + * var client = Stomp.client(url); + * ``` + * + * **Deprecated** + * + * It will be removed in next major version. Please switch to {@link Client} + * using [Client#brokerURL]{@link Client#brokerURL}. + */ + static client(url, protocols) { + // This is a hack to allow another implementation than the standard + // HTML5 WebSocket class. + // + // It is possible to use another class by calling + // + // Stomp.WebSocketClass = MozWebSocket + // + // *prior* to call `Stomp.client()`. + // + // This hack is deprecated and `Stomp.over()` method should be used + // instead. + // See remarks on the function Stomp.over + if (protocols == null) { + protocols = Versions.default.protocolVersions(); + } + const wsFn = () => { + const klass = Stomp.WebSocketClass || WebSocket; + return new klass(url, protocols); + }; + return new CompatClient(wsFn); + } + /** + * This method is an alternative to [Stomp#client]{@link Stomp#client} to let the user + * specify the WebSocket to use (either a standard HTML5 WebSocket or + * a similar object). + * + * In order to support reconnection, the function Client._connect should be callable more than once. + * While reconnecting + * a new instance of underlying transport (TCP Socket, WebSocket or SockJS) will be needed. So, this function + * alternatively allows passing a function that should return a new instance of the underlying socket. + * + * ```javascript + * var client = Stomp.over(function(){ + * return new WebSocket('ws://localhost:15674/ws') + * }); + * ``` + * + * **Deprecated** + * + * It will be removed in next major version. Please switch to {@link Client} + * using [Client#webSocketFactory]{@link Client#webSocketFactory}. + */ + static over(ws) { + let wsFn; + if (typeof ws === 'function') { + wsFn = ws; + } + else { + console.warn('Stomp.over did not receive a factory, auto reconnect will not work. ' + + 'Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over'); + wsFn = () => ws; + } + return new CompatClient(wsFn); + } + } + /** + * In case you need to use a non standard class for WebSocket. + * + * For example when using within NodeJS environment: + * + * ```javascript + * StompJs = require('../../esm5/'); + * Stomp = StompJs.Stomp; + * Stomp.WebSocketClass = require('websocket').w3cwebsocket; + * ``` + * + * **Deprecated** + * + * + * It will be removed in next major version. Please switch to {@link Client} + * using [Client#webSocketFactory]{@link Client#webSocketFactory}. + */ + // tslint:disable-next-line:variable-name + Stomp.WebSocketClass = null; - /** - * Available for backward compatibility, please shift to using {@link Client}. - * - * **Deprecated** - * - * Part of `@stomp/stompjs`. - * - * To upgrade, please follow the [Upgrade Guide](https://stomp-js.github.io/guide/stompjs/upgrading-stompjs.html) - */ - class CompatClient extends Client { - /** - * Available for backward compatibility, please shift to using {@link Client} - * and [Client#webSocketFactory]{@link Client#webSocketFactory}. - * - * **Deprecated** - * - * @internal - */ - constructor(webSocketFactory) { - super(); - /** - * It is no op now. No longer needed. Large packets work out of the box. - */ - this.maxWebSocketFrameSize = 16 * 1024; - this._heartbeatInfo = new HeartbeatInfo(this); - this.reconnect_delay = 0; - this.webSocketFactory = webSocketFactory; - // Default from previous version - this.debug = (...message) => { - console.log(...message); - }; - } - _parseConnect(...args) { - let closeEventCallback; - let connectCallback; - let errorCallback; - let headers = {}; - if (args.length < 2) { - throw new Error('Connect requires at least 2 arguments'); - } - if (typeof args[1] === 'function') { - [headers, connectCallback, errorCallback, closeEventCallback] = args; - } - else { - switch (args.length) { - case 6: - [ - headers.login, - headers.passcode, - connectCallback, - errorCallback, - closeEventCallback, - headers.host, - ] = args; - break; - default: - [ - headers.login, - headers.passcode, - connectCallback, - errorCallback, - closeEventCallback, - ] = args; - } - } - return [headers, connectCallback, errorCallback, closeEventCallback]; - } - /** - * Available for backward compatibility, please shift to using [Client#activate]{@link Client#activate}. - * - * **Deprecated** - * - * The `connect` method accepts different number of arguments and types. See the Overloads list. Use the - * version with headers to pass your broker specific options. - * - * overloads: - * - connect(headers, connectCallback) - * - connect(headers, connectCallback, errorCallback) - * - connect(login, passcode, connectCallback) - * - connect(login, passcode, connectCallback, errorCallback) - * - connect(login, passcode, connectCallback, errorCallback, closeEventCallback) - * - connect(login, passcode, connectCallback, errorCallback, closeEventCallback, host) - * - * params: - * - headers, see [Client#connectHeaders]{@link Client#connectHeaders} - * - connectCallback, see [Client#onConnect]{@link Client#onConnect} - * - errorCallback, see [Client#onStompError]{@link Client#onStompError} - * - closeEventCallback, see [Client#onWebSocketClose]{@link Client#onWebSocketClose} - * - login [String], see [Client#connectHeaders](../classes/Client.html#connectHeaders) - * - passcode [String], [Client#connectHeaders](../classes/Client.html#connectHeaders) - * - host [String], see [Client#connectHeaders](../classes/Client.html#connectHeaders) - * - * To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html) - */ - connect(...args) { - const out = this._parseConnect(...args); - if (out[0]) { - this.connectHeaders = out[0]; - } - if (out[1]) { - this.onConnect = out[1]; - } - if (out[2]) { - this.onStompError = out[2]; - } - if (out[3]) { - this.onWebSocketClose = out[3]; - } - super.activate(); - } - /** - * Available for backward compatibility, please shift to using [Client#deactivate]{@link Client#deactivate}. - * - * **Deprecated** - * - * See: - * [Client#onDisconnect]{@link Client#onDisconnect}, and - * [Client#disconnectHeaders]{@link Client#disconnectHeaders} - * - * To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html) - */ - disconnect(disconnectCallback, headers = {}) { - if (disconnectCallback) { - this.onDisconnect = disconnectCallback; - } - this.disconnectHeaders = headers; - super.deactivate(); - } - /** - * Available for backward compatibility, use [Client#publish]{@link Client#publish}. - * - * Send a message to a named destination. Refer to your STOMP broker documentation for types - * and naming of destinations. The headers will, typically, be available to the subscriber. - * However, there may be special purpose headers corresponding to your STOMP broker. - * - * **Deprecated**, use [Client#publish]{@link Client#publish} - * - * Note: Body must be String. You will need to covert the payload to string in case it is not string (e.g. JSON) - * - * ```javascript - * client.send("/queue/test", {priority: 9}, "Hello, STOMP"); - * - * // If you want to send a message with a body, you must also pass the headers argument. - * client.send("/queue/test", {}, "Hello, STOMP"); - * ``` - * - * To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html) - */ - send(destination, headers = {}, body = '') { - headers = Object.assign({}, headers); - const skipContentLengthHeader = headers['content-length'] === false; - if (skipContentLengthHeader) { - delete headers['content-length']; - } - this.publish({ - destination, - headers: headers, - body, - skipContentLengthHeader, - }); - } - /** - * Available for backward compatibility, renamed to [Client#reconnectDelay]{@link Client#reconnectDelay}. - * - * **Deprecated** - */ - set reconnect_delay(value) { - this.reconnectDelay = value; - } - /** - * Available for backward compatibility, renamed to [Client#webSocket]{@link Client#webSocket}. - * - * **Deprecated** - */ - get ws() { - return this.webSocket; - } - /** - * Available for backward compatibility, renamed to [Client#connectedVersion]{@link Client#connectedVersion}. - * - * **Deprecated** - */ - get version() { - return this.connectedVersion; - } - /** - * Available for backward compatibility, renamed to [Client#onUnhandledMessage]{@link Client#onUnhandledMessage}. - * - * **Deprecated** - */ - get onreceive() { - return this.onUnhandledMessage; - } - /** - * Available for backward compatibility, renamed to [Client#onUnhandledMessage]{@link Client#onUnhandledMessage}. - * - * **Deprecated** - */ - set onreceive(value) { - this.onUnhandledMessage = value; - } - /** - * Available for backward compatibility, renamed to [Client#onUnhandledReceipt]{@link Client#onUnhandledReceipt}. - * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. - * - * **Deprecated** - */ - get onreceipt() { - return this.onUnhandledReceipt; - } - /** - * Available for backward compatibility, renamed to [Client#onUnhandledReceipt]{@link Client#onUnhandledReceipt}. - * - * **Deprecated** - */ - set onreceipt(value) { - this.onUnhandledReceipt = value; - } - /** - * Available for backward compatibility, renamed to [Client#heartbeatIncoming]{@link Client#heartbeatIncoming} - * [Client#heartbeatOutgoing]{@link Client#heartbeatOutgoing}. - * - * **Deprecated** - */ - get heartbeat() { - return this._heartbeatInfo; - } - /** - * Available for backward compatibility, renamed to [Client#heartbeatIncoming]{@link Client#heartbeatIncoming} - * [Client#heartbeatOutgoing]{@link Client#heartbeatOutgoing}. - * - * **Deprecated** - */ - set heartbeat(value) { - this.heartbeatIncoming = value.incoming; - this.heartbeatOutgoing = value.outgoing; - } - } + const __esModule = true; - /** - * STOMP Class, acts like a factory to create {@link Client}. - * - * Part of `@stomp/stompjs`. - * - * **Deprecated** - * - * It will be removed in next major version. Please switch to {@link Client}. - */ - class Stomp { - /** - * This method creates a WebSocket client that is connected to - * the STOMP server located at the url. - * - * ```javascript - * var url = "ws://localhost:61614/stomp"; - * var client = Stomp.client(url); - * ``` - * - * **Deprecated** - * - * It will be removed in next major version. Please switch to {@link Client} - * using [Client#brokerURL]{@link Client#brokerURL}. - */ - static client(url, protocols) { - // This is a hack to allow another implementation than the standard - // HTML5 WebSocket class. - // - // It is possible to use another class by calling - // - // Stomp.WebSocketClass = MozWebSocket - // - // *prior* to call `Stomp.client()`. - // - // This hack is deprecated and `Stomp.over()` method should be used - // instead. - // See remarks on the function Stomp.over - if (protocols == null) { - protocols = Versions.default.protocolVersions(); - } - const wsFn = () => { - const klass = Stomp.WebSocketClass || WebSocket; - return new klass(url, protocols); - }; - return new CompatClient(wsFn); - } - /** - * This method is an alternative to [Stomp#client]{@link Stomp#client} to let the user - * specify the WebSocket to use (either a standard HTML5 WebSocket or - * a similar object). - * - * In order to support reconnection, the function Client._connect should be callable more than once. - * While reconnecting - * a new instance of underlying transport (TCP Socket, WebSocket or SockJS) will be needed. So, this function - * alternatively allows passing a function that should return a new instance of the underlying socket. - * - * ```javascript - * var client = Stomp.over(function(){ - * return new WebSocket('ws://localhost:15674/ws') - * }); - * ``` - * - * **Deprecated** - * - * It will be removed in next major version. Please switch to {@link Client} - * using [Client#webSocketFactory]{@link Client#webSocketFactory}. - */ - static over(ws) { - let wsFn; - if (typeof ws === 'function') { - wsFn = ws; - } - else { - console.warn('Stomp.over did not receive a factory, auto reconnect will not work. ' + - 'Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over'); - wsFn = () => ws; - } - return new CompatClient(wsFn); - } - } - /** - * In case you need to use a non standard class for WebSocket. - * - * For example when using within NodeJS environment: - * - * ```javascript - * StompJs = require('../../esm5/'); - * Stomp = StompJs.Stomp; - * Stomp.WebSocketClass = require('websocket').w3cwebsocket; - * ``` - * - * **Deprecated** - * - * - * It will be removed in next major version. Please switch to {@link Client} - * using [Client#webSocketFactory]{@link Client#webSocketFactory}. - */ - // tslint:disable-next-line:variable-name - Stomp.WebSocketClass = null; - - exports.Client = Client; - exports.CompatClient = CompatClient; - exports.FrameImpl = FrameImpl; - exports.Parser = Parser; - exports.Stomp = Stomp; - exports.StompConfig = StompConfig; - exports.StompHeaders = StompHeaders; - exports.Versions = Versions; - - })); - - } (stomp_umd, stomp_umd.exports)); - - var stomp_umdExports = stomp_umd.exports; - - try { Object.defineProperty(stomp_umdExports, "__" + "esModule", { value: true }); stomp_umdExports.default = stomp_umdExports; } catch (ex) {} - - return stomp_umdExports; + exports.Client = Client; + exports.CompatClient = CompatClient; + exports.FrameImpl = FrameImpl; + exports.Parser = Parser; + exports.Stomp = Stomp; + exports.StompConfig = StompConfig; + exports.StompHeaders = StompHeaders; + exports.Versions = Versions; + exports.__esModule = __esModule; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/4c800ec1/@ui5/webcomponents/dist/Panel.js b/packages/ui5-tooling-modules/test/__snap__/4c800ec1/@ui5/webcomponents/dist/Panel.js index a75c92aed..5594164c9 100644 --- a/packages/ui5-tooling-modules/test/__snap__/4c800ec1/@ui5/webcomponents/dist/Panel.js +++ b/packages/ui5-tooling-modules/test/__snap__/4c800ec1/@ui5/webcomponents/dist/Panel.js @@ -1,206 +1,5 @@ sap.ui.define((function () { 'use strict'; - /** - * @license - * Copyright 2023 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */ - /** - * Map of ARIAMixin properties to attributes - */ - // Shim the global element internals object - // Methods should be fine as noops and properties can generally - // be while on the server. - const ElementInternalsShim = class ElementInternals { - get shadowRoot() { - // Grab the shadow root instance from the Element shim - // to ensure that the shadow root is always available - // to the internals instance even if the mode is 'closed' - return this.__host - .__shadowRoot; - } - constructor(_host) { - this.ariaAtomic = ''; - this.ariaAutoComplete = ''; - this.ariaBrailleLabel = ''; - this.ariaBrailleRoleDescription = ''; - this.ariaBusy = ''; - this.ariaChecked = ''; - this.ariaColCount = ''; - this.ariaColIndex = ''; - this.ariaColSpan = ''; - this.ariaCurrent = ''; - this.ariaDescription = ''; - this.ariaDisabled = ''; - this.ariaExpanded = ''; - this.ariaHasPopup = ''; - this.ariaHidden = ''; - this.ariaInvalid = ''; - this.ariaKeyShortcuts = ''; - this.ariaLabel = ''; - this.ariaLevel = ''; - this.ariaLive = ''; - this.ariaModal = ''; - this.ariaMultiLine = ''; - this.ariaMultiSelectable = ''; - this.ariaOrientation = ''; - this.ariaPlaceholder = ''; - this.ariaPosInSet = ''; - this.ariaPressed = ''; - this.ariaReadOnly = ''; - this.ariaRequired = ''; - this.ariaRoleDescription = ''; - this.ariaRowCount = ''; - this.ariaRowIndex = ''; - this.ariaRowSpan = ''; - this.ariaSelected = ''; - this.ariaSetSize = ''; - this.ariaSort = ''; - this.ariaValueMax = ''; - this.ariaValueMin = ''; - this.ariaValueNow = ''; - this.ariaValueText = ''; - this.role = ''; - this.form = null; - this.labels = []; - this.states = new Set(); - this.validationMessage = ''; - this.validity = {}; - this.willValidate = true; - this.__host = _host; - } - checkValidity() { - // TODO(augustjk) Consider actually implementing logic. - // See https://github.com/lit/lit/issues/3740 - console.warn('`ElementInternals.checkValidity()` was called on the server.' + - 'This method always returns true.'); - return true; - } - reportValidity() { - return true; - } - setFormValue() { } - setValidity() { } - }; - - const attributes = new WeakMap(); - const attributesForElement = element => { - let attrs = attributes.get(element); - if (attrs === undefined) { - attributes.set(element, attrs = new Map()); - } - return attrs; - }; - const ElementShim = class Element { - constructor() { - this.__shadowRootMode = null; - this.__shadowRoot = null; - this.__internals = null; - } - get attributes() { - return Array.from(attributesForElement(this)).map(([name, value]) => ({ - name, - value - })); - } - get shadowRoot() { - if (this.__shadowRootMode === "closed") { - return null; - } - return this.__shadowRoot; - } - get localName() { - return this.constructor.__localName; - } - get tagName() { - return this.localName?.toUpperCase(); - } - setAttribute(name, value) { - attributesForElement(this).set(name, String(value)); - } - removeAttribute(name) { - attributesForElement(this).delete(name); - } - toggleAttribute(name, force) { - if (this.hasAttribute(name)) { - if (force === undefined || !force) { - this.removeAttribute(name); - return false; - } - } else { - if (force === undefined || force) { - this.setAttribute(name, ""); - return true; - } else { - return false; - } - } - return true; - } - hasAttribute(name) { - return attributesForElement(this).has(name); - } - attachShadow(init) { - const shadowRoot = { - host: this - }; - this.__shadowRootMode = init.mode; - if (init && init.mode === "open") { - this.__shadowRoot = shadowRoot; - } - return shadowRoot; - } - attachInternals() { - if (this.__internals !== null) { - throw new Error(`Failed to execute 'attachInternals' on 'HTMLElement': ` + `ElementInternals for the specified element was already attached.`); - } - const internals = new ElementInternalsShim(this); - this.__internals = internals; - return internals; - } - getAttribute(name) { - const value = attributesForElement(this).get(name); - return value ?? null; - } - }; - const ElementShimWithRealType = ElementShim; - const HTMLElementShim = class HTMLElement extends ElementShim {}; - const HTMLElementShimWithRealType = HTMLElementShim; - const CustomElementRegistryShim = class CustomElementRegistry { - constructor() { - this.__definitions = new Map(); - } - define(name, ctor) { - if (this.__definitions.has(name)) { - { - throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': ` + `the name "${name}" has already been used with this registry`); - } - } - ctor.__localName = name; - this.__definitions.set(name, { - ctor, - observedAttributes: ctor.observedAttributes ?? [] - }); - } - get(name) { - const definition = this.__definitions.get(name); - return definition?.ctor; - } - }; - const CustomElementRegistryShimWithRealType = CustomElementRegistryShim; - const customElements$1 = new CustomElementRegistryShimWithRealType(); - - /* eslint-disable max-classes-per-file */ - globalThis.HTMLElement ??= HTMLElementShimWithRealType; - globalThis.Element ??= ElementShimWithRealType; - globalThis.customElements ??= customElements$1; - class NodeShim { - } - globalThis.Node ??= NodeShim; - class FileListShim { - } - globalThis.FileList ??= FileListShim; - var class2type = {}; var hasOwn = class2type.hasOwnProperty; var toString = class2type.toString; @@ -2907,7 +2706,7 @@ sap.ui.define((function () { 'use strict'; * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - var t$1;const i$1=globalThis,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=void 0===i$1.document?{createTreeWalker:()=>({})}: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,x=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),T=x(1),b=x(2),w=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 x=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+x):s+n+(-2===v?(e.push(void 0),i):x);}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!==w,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 k(i.insertBefore(u$1(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; + 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}; /** * @license @@ -2920,20 +2719,20 @@ sap.ui.define((function () { 'use strict'; * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const {I:l$1}=Z,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$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;}}; /** * @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$1=0,A=p$1.length-1;for(;j<=k&&w$1<=A;)if(null===a$1[j])j++;else if(null===a$1[k])k--;else if(h[j]===v[w$1])m$1[w$1]=f(a$1[j],p$1[w$1]),j++,w$1++;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$1])m$1[w$1]=f(a$1[k],p$1[w$1]),c$1(s,a$1[j],a$1[k]),k--,w$1++;else if(void 0===y&&(y=u(v,w$1,A),x=u(h,j,k)),y.has(h[j]))if(y.has(h[k])){const e=x.get(v[w$1]),t=void 0!==e?a$1[e]:null;if(null===t){const e=c$1(s,a$1[j]);f(e,p$1[w$1]),m$1[w$1]=e;}else m$1[w$1]=f(t,p$1[w$1]),c$1(s,a$1[j],t),a$1[e]=null;w$1++;}else p(a$1[k]),k--;else p(a$1[j]),j++;for(;w$1<=A;){const e=c$1(s,m$1[A+1]);f(e,p$1[w$1]),m$1[w$1++]=e;}for(;j<=k;){const e=a$1[j++];null!==e&&p(e);}return this.ut=v,a(s,m$1),w}}); + 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}}); /** * @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 w}}); + */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}}); // @ts-nocheck /* eslint-disable */ @@ -3000,7 +2799,7 @@ sap.ui.define((function () { 'use strict'; } } } - return w; + return T; } } const styleMap = e$1(StyleMapDirective); @@ -3015,11 +2814,11 @@ sap.ui.define((function () { 'use strict'; * @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===w)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{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; const effectiveHtml = (strings, ...values) => { const litStatic = getFeature("LitStatic"); - const fn = litStatic ? litStatic.html : T; + const fn = litStatic ? litStatic.html : x; return fn(strings, ...values); }; const effectiveSvg = (strings, ...values) => { @@ -3032,7 +2831,7 @@ sap.ui.define((function () { 'use strict'; if (openUI5Enablement) { templateResult = openUI5Enablement.wrapTemplateResultInBusyMarkup(effectiveHtml, options.host, templateResult); } - B(templateResult, container, options); + D(templateResult, container, options); }; const scopeTag = (tag, tags, suffix) => { const litStatic = getFeature("LitStatic"); diff --git a/packages/ui5-tooling-modules/test/__snap__/50592569/@octokit/core.js b/packages/ui5-tooling-modules/test/__snap__/50592569/@octokit/core.js index 2c58ca7bf..207f8110d 100644 --- a/packages/ui5-tooling-modules/test/__snap__/50592569/@octokit/core.js +++ b/packages/ui5-tooling-modules/test/__snap__/50592569/@octokit/core.js @@ -397,10 +397,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; beforeAfterHook.exports.Singular = Hook.Singular; var Collection = beforeAfterHook.exports.Collection = Hook.Collection; - var isPlainObject$1 = {}; - - Object.defineProperty(isPlainObject$1, '__esModule', { value: true }); - /*! * is-plain-object * @@ -434,8 +430,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return true; } - var isPlainObject_2 = isPlainObject$1.isPlainObject = isPlainObject; - // pkg/dist-src/util/lowercase-keys.js function lowercaseKeys(object) { if (!object) { @@ -449,7 +443,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function mergeDeep(defaults, options) { const result = Object.assign({}, defaults); Object.keys(options).forEach((key) => { - if (isPlainObject_2(options[key])) { + if (isPlainObject(options[key])) { if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); else @@ -950,7 +944,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // pkg/dist-src/fetch-wrapper.js function fetchWrapper(requestOptions) { const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - if (isPlainObject_2(requestOptions.body) || Array.isArray(requestOptions.body)) { + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } let headers = {}; diff --git a/packages/ui5-tooling-modules/test/__snap__/906ae360/ui5-app/bundledefs/firebase.js b/packages/ui5-tooling-modules/test/__snap__/906ae360/ui5-app/bundledefs/firebase.js index 5d2e96ebd..79c869160 100644 --- a/packages/ui5-tooling-modules/test/__snap__/906ae360/ui5-app/bundledefs/firebase.js +++ b/packages/ui5-tooling-modules/test/__snap__/906ae360/ui5-app/bundledefs/firebase.js @@ -27,2316 +27,2374 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return a; } - var index_cjs$2 = {}; - - var global$3 = (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$3.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global$3.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$3 = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop$3() {} - - var on = noop$3; - var addListener$2 = noop$3; - var once = noop$3; - var off = noop$3; - var removeListener = noop$3; - var removeAllListeners$2 = noop$3; - var emit = noop$3; - - function binding$1(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$1 = global$3.performance || {}; - var performanceNow = - performance$1.now || - performance$1.mozNow || - performance$1.msNow || - performance$1.oNow || - performance$1.webkitNow || - function(){ return (new Date()).getTime() }; + var index_cjs$4 = {}; - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance$1)*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 index_cjs$3 = {}; - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } + var index_cjs$2 = {}; - var browser$1$1 = { - nextTick: nextTick, - title: title, - browser: browser$1, - env: env, - argv: argv, - version: version$3, - versions: versions, - on: on, - addListener: addListener$2, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners$2, - emit: emit, - binding: binding$1, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; + var tslib$1 = {exports: {}}; - const CONSTANTS = { - NODE_CLIENT: false, - NODE_ADMIN: false, - SDK_VERSION: "${JSCORE_VERSION}" - }; - const assert$h = 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"); + (function (module) { + var __extends; + var __assign; + var __rest; + var __decorate; + var __param; + var __esDecorate; + var __runInitializers; + var __propKey; + var __setFunctionName; + var __metadata; + var __awaiter; + var __generator; + var __exportStar; + var __values; + var __read; + var __spread; + var __spreadArrays; + var __spreadArray; + var __await; + var __asyncGenerator; + var __asyncDelegator; + var __asyncValues; + var __makeTemplateObject; + var __importStar; + var __importDefault; + var __classPrivateFieldGet; + var __classPrivateFieldSet; + var __classPrivateFieldIn; + var __createBinding; + var __addDisposableResource; + var __disposeResources; + (function (factory) { + var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {}; + { + factory(createExporter(root, createExporter(module.exports))); } - 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; + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { + value: true + }); + } else { + exports.__esModule = true; } } - 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 function (id, v) { + return exports[id] = previous ? previous(id, v) : v; + }; } - 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(); + })(function (exporter) { + var 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]; + }); + __extends = 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; } - 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); - } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + __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 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; - } + return t; + }); + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[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 = {}; + return t; + }; + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return (c > 3 && r && Object.defineProperty(target, key, r), r); + }; + __param = function (paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; + }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; } - 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$3 !== "undefined") { - return global$3; - } - 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}`]; - }; - let Deferred$1 = 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); + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { + get: descriptor.get, + set: descriptor.set + } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; }; - } - }; - 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$3.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 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$2(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$1(obj) { - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - return false; - } - } - return true; - } - function map$2(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$1(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$1(aProp) && isObject$1(bProp)) { - if (!deepEqual$1(aProp, bProp)) { - return false; + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } - } else if (aProp !== bProp) { - return false; - } - } - for (const k of bKeys) { - if (!aKeys.includes(k)) { - return false; - } - } - return true; - } - function isObject$1(thing) { - return thing !== null && typeof thing === "object"; - } - function promiseWithTimeout(promise, timeInMS = 2000) { - const deferredPromise = new Deferred$1(); - 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)); + return useValue ? value : void 0; + }; + __propKey = function (x) { + return typeof x === "symbol" ? x : ("").concat(x); + }; + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? ("[").concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { + configurable: true, + value: prefix ? ("").concat(prefix, " ", name) : name }); - } 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; + }; + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); } - } - 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; + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } else { - if (i < 60) { - f = b & c | d & (b | c); - k = 2400959708; - } else { - f = b ^ c ^ d; - k = 3395469782; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - } - 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; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + __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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return (g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g); + function verb(n) { + return function (v) { + return step([n, v]); + }; } - 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; + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while ((g && (g = 0, op[0] && (_ = 0)), _)) 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 + }; } - } - 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; + }; + __exportStar = function (m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + __createBinding = Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || (("get" in desc) ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; } - } - 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 + Object.defineProperty(o, k2, desc); + } : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + __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 + }; + } }; - } - if (observer.next === undefined) { - observer.next = noop$2; - } - if (observer.error === undefined) { - observer.error = noop$2; - } - if (observer.complete === undefined) { - observer.complete = noop$2; - } - const unsub = this.unsubscribeOne.bind(this, this.observers.length); - if (this.finalized) { - this.task.then(() => { + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + __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 (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) { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + }; + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; + }; + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; (j++, k++)) r[k] = a[j]; + return r; + }; + __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)); + }; + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return (i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { try { - fn(this.observers[i]); + step(g[n](v)); } catch (e) { - if (typeof console !== "undefined" && console.error) { - console.error(e); - } + settle(q[0][3], 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 step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - }); - }; - } - 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$2() {} - 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$h(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$1 = 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$1) { - 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 fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } + }; + __asyncDelegator = function (o) { + var i, p; + return (i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i); + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: false + } : f ? f(v) : v; + } : f; + } + }; + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && (function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v), settle(resolve, reject, v.done, v.value)); + }); + }); + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + }; + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + return cooked; + }; + var __setModuleDefault = Object.create ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v + }); + } : function (o, v) { + o["default"] = v; + }; + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + __importDefault = function (mod) { + return mod && mod.__esModule ? mod : { + "default": mod + }; + }; + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value); + }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function () { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ + value: value, + dispose: dispose, + async: async + }); + } else if (async) { + env.stack.push({ + async: true + }); + } + return value; + }; + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return (e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e); + }; + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return (s = 0, env.stack.push(r), Promise.resolve().then(next)); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return (s |= 2, Promise.resolve(result).then(next, function (e) { + fail(e); + return next(); + })); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); + }); + })(tslib$1); + var tslibExports = tslib$1.exports; + + var global$3 = (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 ordinal(i) { - if (!Number.isFinite(i)) { - return `${i}`; - } - return i + indicator(i); + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } - 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"; + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$3.setTimeout === 'function') { + cachedSetTimeout = setTimeout; } - function getModularInstance(service) { - if (service && service._delegate) { - return service._delegate; - } else { - return service; - } + if (typeof global$3.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; } - var index_esm2017$2 = /*#__PURE__*/Object.freeze({ - __proto__: null, - CONSTANTS: CONSTANTS, - DecodeBase64StringError: DecodeBase64StringError, - Deferred: Deferred$1, - ErrorFactory: ErrorFactory, - FirebaseError: FirebaseError, - MAX_VALUE_MILLIS: MAX_VALUE_MILLIS, - RANDOM_FACTOR: RANDOM_FACTOR, - Sha1: Sha1, - areCookiesEnabled: areCookiesEnabled, - assert: assert$h, - 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$1, - 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, - isElectron: isElectron, - isEmpty: isEmpty$1, - 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$2, - ordinal: ordinal, - promiseWithTimeout: promiseWithTimeout, - querystring: querystring, - querystringDecode: querystringDecode, - safeGet: safeGet, - stringLength: stringLength, - stringToByteArray: stringToByteArray, - stringify: stringify$2, - uuidv4: uuidv4, - validateArgCount: validateArgCount, - validateCallback: validateCallback, - validateContextObject: validateContextObject, - validateIndexedDBOpenable: validateIndexedDBOpenable, - validateNamespace: validateNamespace - }); + 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); + } + } + - /** - * 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; - } } + 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); + } + } + - /** - * @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 mulitple 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$1(); - 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/can not 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 */; } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -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. - */ - /** - * 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()); - } + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } } - var index_esm2017$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - Component: Component, - ComponentContainer: ComponentContainer, - Provider: Provider - }); + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - var index_cjs$1 = {}; + 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$2 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; - var tslib = {exports: {}}; + function noop$3() {} - (function (module) { - var __extends; - var __assign; - var __rest; - var __decorate; - var __param; - var __esDecorate; - var __runInitializers; - var __propKey; - var __setFunctionName; - var __metadata; - var __awaiter; - var __generator; - var __exportStar; - var __values; - var __read; - var __spread; - var __spreadArrays; - var __spreadArray; - var __await; - var __asyncGenerator; - var __asyncDelegator; - var __asyncValues; - var __makeTemplateObject; - var __importStar; - var __importDefault; - var __classPrivateFieldGet; - var __classPrivateFieldSet; - var __classPrivateFieldIn; - var __createBinding; - var __addDisposableResource; - var __disposeResources; - (function (factory) { - var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {}; - { - factory(createExporter(root, createExporter(module.exports))); + var on = noop$3; + var addListener$2 = noop$3; + var once = noop$3; + var off = noop$3; + var removeListener = noop$3; + var removeAllListeners$2 = noop$3; + var emit = noop$3; + + function binding$1(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$1 = global$3.performance || {}; + var performanceNow = + performance$1.now || + performance$1.mozNow || + performance$1.msNow || + performance$1.oNow || + performance$1.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$1)*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; } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { - value: true - }); - } else { - exports.__esModule = true; + } + 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$2, + versions: versions, + on: on, + addListener: addListener$2, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners$2, + emit: emit, + binding: binding$1, + 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$h = 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; } } - return function (id, v) { - return exports[id] = previous ? previous(id, v) : v; - }; + output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); } - })(function (exporter) { - var 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]; - }); - __extends = 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 __()); - }; - __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 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(); } - return t; - }); - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + 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 t; - }; - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return (c > 3 && r && Object.defineProperty(target, key, r), r); - }; - __param = function (paramIndex, decorator) { - return function (target, key) { - decorator(target, key, paramIndex); - }; - }; - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { - get: descriptor.get, - set: descriptor.set - } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); else descriptor[key] = _; + } + 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; } } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - __propKey = function (x) { - return typeof x === "symbol" ? x : ("").concat(x); - }; - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? ("[").concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { - configurable: true, - value: prefix ? ("").concat(prefix, " ", name) : name - }); - }; - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); + } + } + }; + 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 = {}; } - 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()); - }); - }; - __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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return (g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { - return this; - }), g); - function verb(n) { - return function (v) { - return step([n, v]); - }; + 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$3 !== "undefined") { + return global$3; + } + 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}`]; + }; + let Deferred$1 = 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); } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while ((g && (g = 0, op[0] && (_ = 0)), _)) 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 (typeof callback === "function") { + this.promise.catch(() => {}); + if (callback.length === 1) { + callback(error); + } else { + callback(error, value); } - if (op[0] & 5) throw op[1]; - return { - value: op[0] ? op[1] : void 0, - done: true - }; - } - }; - __exportStar = function (m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - __createBinding = Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || (("get" in desc) ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; } - Object.defineProperty(o, k2, desc); - } : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; }; - __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 - }; + } + }; + 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$3.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 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); }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - __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; - }; - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); - return ar; - }; - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; (j++, k++)) r[k] = a[j]; - return r; - }; - __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)); - }; - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return (i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function awaitReturn(f) { - return function (v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); - } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); - } - }; - __asyncDelegator = function (o) { - var i, p; - return (i = {}, verb("next"), verb("throw", function (e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function () { - return this; - }, i); - function verb(n, f) { - i[n] = o[n] ? function (v) { - return (p = !p) ? { - value: __await(o[n](v)), - done: false - } : f ? f(v) : v; - } : f; - } - }; - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && (function (v) { - return new Promise(function (resolve, reject) { - (v = o[n](v), settle(resolve, reject, v.done, v.value)); - }); - }); + 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$2(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$1(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; + } + function map$2(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$1(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$1(aProp) && isObject$1(bProp)) { + if (!deepEqual$1(aProp, bProp)) { + return false; } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); + } else if (aProp !== bProp) { + return false; + } + } + for (const k of bKeys) { + if (!aKeys.includes(k)) { + return false; + } + } + return true; + } + function isObject$1(thing) { + return thing !== null && typeof thing === "object"; + } + function promiseWithTimeout(promise, timeInMS = 2000) { + const deferredPromise = new Deferred$1(); + 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; } - }; - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { - value: raw - }); - } else { - cooked.raw = raw; + } 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; } - return cooked; - }; - var __setModuleDefault = Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); - } : function (o, v) { - o["default"] = v; - }; - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - __importDefault = function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; - }; - __classPrivateFieldGet = function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value); - }; - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - __addDisposableResource = function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; + } + 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; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + } else { + if (i < 60) { + f = b & c | d & (b | c); + k = 2400959708; + } else { + f = b ^ c ^ d; + k = 3395469782; } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function () { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); - } - }; - env.stack.push({ - value: value, - dispose: dispose, - async: async - }); - } else if (async) { - env.stack.push({ - async: true - }); } - return value; - }; - var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return (e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e); - }; - __disposeResources = function (env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; + 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; + } } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return (s = 0, env.stack.push(r), Promise.resolve().then(next)); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return (s |= 2, Promise.resolve(result).then(next, function (e) { - fail(e); - return next(); - })); - } else s |= 1; - } catch (e) { - fail(e); + 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; } } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; } - return next(); - }; - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); - exporter("__addDisposableResource", __addDisposableResource); - exporter("__disposeResources", __disposeResources); - }); - })(tslib); - var tslibExports = tslib.exports; + } + 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$2; + } + if (observer.error === undefined) { + observer.error = noop$2; + } + if (observer.complete === undefined) { + observer.complete = noop$2; + } + 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$2() {} + 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$h(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$1 = 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$1) { + 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$1, + ErrorFactory: ErrorFactory, + FirebaseError: FirebaseError, + MAX_VALUE_MILLIS: MAX_VALUE_MILLIS, + RANDOM_FACTOR: RANDOM_FACTOR, + Sha1: Sha1, + areCookiesEnabled: areCookiesEnabled, + assert: assert$h, + 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$1, + 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, + isElectron: isElectron, + isEmpty: isEmpty$1, + 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$2, + ordinal: ordinal, + promiseWithTimeout: promiseWithTimeout, + querystring: querystring, + querystringDecode: querystringDecode, + safeGet: safeGet, + stringLength: stringLength, + stringToByteArray: stringToByteArray, + stringify: stringify$2, + uuidv4: uuidv4, + validateArgCount: validateArgCount, + validateCallback: validateCallback, + validateContextObject: validateContextObject, + validateIndexedDBOpenable: validateIndexedDBOpenable, + validateNamespace: validateNamespace + }); + + var require$$4$2 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); + + Object.defineProperty(index_cjs$2, '__esModule', { value: true }); + + var tslib = tslibExports; + var util$q = require$$4$2; + + /** + * Component for service name T, e.g. `auth`, `auth-internal` + */ + var Component = /** @class */ (function () { + /** + * + * @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 + */ + function Component(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; + } + Component.prototype.setInstantiationMode = function (mode) { + this.instantiationMode = mode; + return this; + }; + Component.prototype.setMultipleInstances = function (multipleInstances) { + this.multipleInstances = multipleInstances; + return this; + }; + Component.prototype.setServiceProps = function (props) { + this.serviceProps = props; + return this; + }; + Component.prototype.setInstanceCreatedCallback = function (callback) { + this.onInstanceCreated = callback; + return this; + }; + return Component; + }()); + + /** + * @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. + */ + var 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 + */ + var Provider = /** @class */ (function () { + function Provider(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 mulitple instances of a service + * if this.component.multipleInstances is true. + */ + Provider.prototype.get = function (identifier) { + // if multipleInstances is not supported, use the default name + var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + if (!this.instancesDeferred.has(normalizedIdentifier)) { + var deferred = new util$q.Deferred(); + this.instancesDeferred.set(normalizedIdentifier, deferred); + if (this.isInitialized(normalizedIdentifier) || + this.shouldAutoInitialize()) { + // initialize the service if it can be auto-initialized + try { + var 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; + }; + Provider.prototype.getImmediate = function (options) { + var _a; + // if multipleInstances is not supported, use the default name + var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); + var 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/can not be auto-initialized at the moment, return null if the optional flag is set, or throw + if (optional) { + return null; + } + else { + throw Error("Service ".concat(this.name, " is not available")); + } + } + }; + Provider.prototype.getComponent = function () { + return this.component; + }; + Provider.prototype.setComponent = function (component) { + var e_1, _a; + if (component.name !== this.name) { + throw Error("Mismatching Component ".concat(component.name, " for Provider ").concat(this.name, ".")); + } + if (this.component) { + throw Error("Component for ".concat(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? + } + } + try { + // 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 (var _b = tslib.__values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) { + var _d = tslib.__read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1]; + var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + try { + // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. + var 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. + } + } + } + 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; } + } + }; + Provider.prototype.clearInstance = function (identifier) { + if (identifier === void 0) { 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? + Provider.prototype.delete = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var services; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + services = Array.from(this.instances.values()); + return [4 /*yield*/, Promise.all(tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(services + .filter(function (service) { return 'INTERNAL' in service; }) // legacy services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(function (service) { return service.INTERNAL.delete(); })), false), tslib.__read(services + .filter(function (service) { return '_delete' in service; }) // modularized services + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map(function (service) { return service._delete(); })), false))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + Provider.prototype.isComponentSet = function () { + return this.component != null; + }; + Provider.prototype.isInitialized = function (identifier) { + if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } + return this.instances.has(identifier); + }; + Provider.prototype.getOptions = function (identifier) { + if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } + return this.instancesOptions.get(identifier) || {}; + }; + Provider.prototype.initialize = function (opts) { + var e_2, _a; + if (opts === void 0) { opts = {}; } + var _b = opts.options, options = _b === void 0 ? {} : _b; + var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); + if (this.isInitialized(normalizedIdentifier)) { + throw Error("".concat(this.name, "(").concat(normalizedIdentifier, ") has already been initialized")); + } + if (!this.isComponentSet()) { + throw Error("Component ".concat(this.name, " has not been registered yet")); + } + var instance = this.getOrInitializeService({ + instanceIdentifier: normalizedIdentifier, + options: options + }); + try { + // resolve any pending promise waiting for the service instance + for (var _c = tslib.__values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) { + var _e = tslib.__read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1]; + var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); + if (normalizedIdentifier === normalizedDeferredIdentifier) { + instanceDeferred.resolve(instance); + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + 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 + */ + Provider.prototype.onInit = function (callback, identifier) { + var _a; + var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); + var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); + existingCallbacks.add(callback); + this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); + var existingInstance = this.instances.get(normalizedIdentifier); + if (existingInstance) { + callback(existingInstance, normalizedIdentifier); + } + return function () { + existingCallbacks.delete(callback); + }; + }; + /** + * Invoke onInit callbacks synchronously + * @param instance the service instance` + */ + Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) { + var e_3, _a; + var callbacks = this.onInitCallbacks.get(identifier); + if (!callbacks) { + return; + } + try { + for (var callbacks_1 = tslib.__values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { + var callback = callbacks_1_1.value; + try { + callback(instance, identifier); + } + catch (_b) { + // ignore errors in the onInit callback + } + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); + } + finally { if (e_3) throw e_3.error; } + } + }; + Provider.prototype.getOrInitializeService = function (_a) { + var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b; + var instance = this.instances.get(instanceIdentifier); + if (!instance && this.component) { + instance = this.component.instanceFactory(this.container, { + instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), + options: 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 (_c) { + // ignore errors in the onInstanceCreatedCallback + } + } + } + return instance || null; + }; + Provider.prototype.normalizeInstanceIdentifier = function (identifier) { + if (identifier === void 0) { 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. + } + }; + Provider.prototype.shouldAutoInitialize = function () { + return (!!this.component && + this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */); + }; + return Provider; + }()); + // 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` + */ + var ComponentContainer = /** @class */ (function () { + function ComponentContainer(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 + */ + ComponentContainer.prototype.addComponent = function (component) { + var provider = this.getProvider(component.name); + if (provider.isComponentSet()) { + throw new Error("Component ".concat(component.name, " has already been registered with ").concat(this.name)); + } + provider.setComponent(component); + }; + ComponentContainer.prototype.addOrOverwriteComponent = function (component) { + var 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. + */ + ComponentContainer.prototype.getProvider = function (name) { + if (this.providers.has(name)) { + return this.providers.get(name); + } + // create a Provider for a service that hasn't registered with Firebase + var provider = new Provider(name, this); + this.providers.set(name, provider); + return provider; + }; + ComponentContainer.prototype.getProviders = function () { + return Array.from(this.providers.values()); + }; + return ComponentContainer; + }()); + + index_cjs$2.Component = Component; + index_cjs$2.ComponentContainer = ComponentContainer; + index_cjs$2.Provider = Provider; + + var index_cjs$1 = {}; (function (exports) { @@ -2612,10 +2670,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } (index_cjs$1)); - var build = {}; - - var wrapIdbValue$1 = {}; - const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); let idbProxyableTypes; @@ -2800,16 +2854,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } const unwrap = (value) => reverseTransformCache.get(value); - wrapIdbValue$1.instanceOfAny = instanceOfAny; - wrapIdbValue$1.replaceTraps = replaceTraps; - wrapIdbValue$1.reverseTransformCache = reverseTransformCache; - wrapIdbValue$1.unwrap = unwrap; - wrapIdbValue$1.wrap = wrap; - - Object.defineProperty(build, '__esModule', { value: true }); - - var wrapIdbValue = wrapIdbValue$1; - /** * Open a database. * @@ -2819,10 +2863,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { const request = indexedDB.open(name, version); - const openPromise = wrapIdbValue.wrap(request); + const openPromise = wrap(request); if (upgrade) { request.addEventListener('upgradeneeded', (event) => { - upgrade(wrapIdbValue.wrap(request.result), event.oldVersion, event.newVersion, wrapIdbValue.wrap(request.transaction), event); + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); }); } if (blocked) { @@ -2853,7 +2897,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 event.oldVersion, event)); } - return wrapIdbValue.wrap(request).then(() => undefined); + return wrap(request).then(() => undefined); } const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; @@ -2895,1194 +2939,1412 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; cachedMethods.set(prop, method); return method; } - wrapIdbValue.replaceTraps((oldTraps) => ({ + 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), })); - build.unwrap = wrapIdbValue.unwrap; - build.wrap = wrapIdbValue.wrap; - build.deleteDB = deleteDB; - var openDB_1 = build.openDB = openDB; + var build = /*#__PURE__*/Object.freeze({ + __proto__: null, + deleteDB: deleteDB, + openDB: openDB, + unwrap: unwrap, + wrap: wrap + }); - /** - * @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 */; - } + var require$$4$1 = /*@__PURE__*/getAugmentedNamespace(build); - const name$p = "@firebase/app"; - const version$1$1 = "0.10.10"; + (function (exports) { - /** - * @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$1 = new index_cjs$1.Logger('@firebase/app'); + Object.defineProperty(exports, '__esModule', { value: true }); - const name$o = "@firebase/app-compat"; + var component = index_cjs$2; + var tslib = tslibExports; + var logger$1 = index_cjs$1; + var util = require$$4$2; + var idb = require$$4$1; - const name$n = "@firebase/analytics-compat"; + /** + * @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. + */ + var PlatformLoggerServiceImpl = /** @class */ (function () { + function PlatformLoggerServiceImpl(container) { + this.container = container; + } + // In initial implementation, this will be called by installations on + // auth token refresh, and installations will send this string. + PlatformLoggerServiceImpl.prototype.getPlatformInfoString = function () { + var providers = this.container.getProviders(); + // Loop through providers and get library/version pairs from any that are + // version components. + return providers + .map(function (provider) { + if (isVersionServiceProvider(provider)) { + var service = provider.getImmediate(); + return "".concat(service.library, "/").concat(service.version); + } + else { + return null; + } + }) + .filter(function (logString) { return logString; }) + .join(' '); + }; + return PlatformLoggerServiceImpl; + }()); + /** + * + * @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) { + var component = provider.getComponent(); + return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */; + } - const name$m = "@firebase/analytics"; + var name$p = "@firebase/app"; + var version$1 = "0.10.10"; - const name$l = "@firebase/app-check-compat"; + /** + * @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. + */ + var logger = new logger$1.Logger('@firebase/app'); - const name$k = "@firebase/app-check"; + var name$o = "@firebase/app-compat"; - const name$j = "@firebase/auth"; + var name$n = "@firebase/analytics-compat"; - const name$i = "@firebase/auth-compat"; + var name$m = "@firebase/analytics"; - const name$h = "@firebase/database"; + var name$l = "@firebase/app-check-compat"; - const name$g = "@firebase/database-compat"; + var name$k = "@firebase/app-check"; - const name$f = "@firebase/functions"; + var name$j = "@firebase/auth"; - const name$e = "@firebase/functions-compat"; + var name$i = "@firebase/auth-compat"; - const name$d = "@firebase/installations"; + var name$h = "@firebase/database"; - const name$c = "@firebase/installations-compat"; + var name$g = "@firebase/database-compat"; - const name$b = "@firebase/messaging"; + var name$f = "@firebase/functions"; - const name$a = "@firebase/messaging-compat"; + var name$e = "@firebase/functions-compat"; - const name$9 = "@firebase/performance"; + var name$d = "@firebase/installations"; - const name$8 = "@firebase/performance-compat"; + var name$c = "@firebase/installations-compat"; - const name$7 = "@firebase/remote-config"; + var name$b = "@firebase/messaging"; - const name$6 = "@firebase/remote-config-compat"; + var name$a = "@firebase/messaging-compat"; - const name$5 = "@firebase/storage"; + var name$9 = "@firebase/performance"; - const name$4 = "@firebase/storage-compat"; + var name$8 = "@firebase/performance-compat"; - const name$3 = "@firebase/firestore"; + var name$7 = "@firebase/remote-config"; - const name$2 = "@firebase/vertexai-preview"; + var name$6 = "@firebase/remote-config-compat"; - const name$1 = "@firebase/firestore-compat"; + var name$5 = "@firebase/storage"; - const name = "firebase"; - const version$2 = "10.13.1"; + var name$4 = "@firebase/storage-compat"; - /** - * @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$p]: 'fire-core', - [name$o]: 'fire-core-compat', - [name$m]: 'fire-analytics', - [name$n]: 'fire-analytics-compat', - [name$k]: 'fire-app-check', - [name$l]: 'fire-app-check-compat', - [name$j]: 'fire-auth', - [name$i]: 'fire-auth-compat', - [name$h]: 'fire-rtdb', - [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' - }; + var name$3 = "@firebase/firestore"; - /** - * @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$1.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$1.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(); - } + var name$2 = "@firebase/vertexai-preview"; - /** - * @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); + var name$1 = "@firebase/firestore-compat"; - /** - * @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 }); - } - } - } + var name = "firebase"; + var version = "10.13.1"; - /** - * @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$p, version$1$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. + */ + var _a$1; + /** + * The default app name + * + * @internal + */ + var DEFAULT_ENTRY_NAME = '[DEFAULT]'; + var PLATFORM_LOG_STRING = (_a$1 = {}, + _a$1[name$p] = 'fire-core', + _a$1[name$o] = 'fire-core-compat', + _a$1[name$m] = 'fire-analytics', + _a$1[name$n] = 'fire-analytics-compat', + _a$1[name$k] = 'fire-app-check', + _a$1[name$l] = 'fire-app-check-compat', + _a$1[name$j] = 'fire-auth', + _a$1[name$i] = 'fire-auth-compat', + _a$1[name$h] = 'fire-rtdb', + _a$1[name$g] = 'fire-rtdb-compat', + _a$1[name$f] = 'fire-fn', + _a$1[name$e] = 'fire-fn-compat', + _a$1[name$d] = 'fire-iid', + _a$1[name$c] = 'fire-iid-compat', + _a$1[name$b] = 'fire-fcm', + _a$1[name$a] = 'fire-fcm-compat', + _a$1[name$9] = 'fire-perf', + _a$1[name$8] = 'fire-perf-compat', + _a$1[name$7] = 'fire-rc', + _a$1[name$6] = 'fire-rc-compat', + _a$1[name$5] = 'fire-gcs', + _a$1[name$4] = 'fire-gcs-compat', + _a$1[name$3] = 'fire-fst', + _a$1[name$1] = 'fire-fst-compat', + _a$1[name$2] = 'fire-vertex', + _a$1['fire-js'] = 'fire-js', + _a$1[name] = 'fire-js-all', + _a$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. + */ + /** + * @internal + */ + var _apps = new Map(); + /** + * @internal + */ + var _serverApps = new Map(); + /** + * Registered components. + * + * @internal + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var _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 ".concat(component.name, " failed to register with FirebaseApp ").concat(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) { + var e_1, _a, e_2, _b; + var componentName = component.name; + if (_components.has(componentName)) { + logger.debug("There were multiple attempts to register component ".concat(componentName, ".")); + return false; + } + _components.set(componentName, component); + try { + // add the component to existing app instances + for (var _c = tslib.__values(_apps.values()), _d = _c.next(); !_d.done; _d = _c.next()) { + var app = _d.value; + _addComponent(app, component); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (var _e = tslib.__values(_serverApps.values()), _f = _e.next(); !_f.done; _f = _e.next()) { + var serverApp = _f.value; + _addComponent(serverApp, component); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_f && !_f.done && (_b = _e.return)) _b.call(_e); + } + finally { if (e_2) throw e_2.error; } + } + 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) { + var 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) { + if (instanceIdentifier === void 0) { 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. + */ + var _a; + var ERRORS = (_a = {}, + _a["no-app" /* AppError.NO_APP */] = "No Firebase App '{$appName}' has been created - " + + 'call initializeApp() first', + _a["bad-app-name" /* AppError.BAD_APP_NAME */] = "Illegal App name: '{$appName}'", + _a["duplicate-app" /* AppError.DUPLICATE_APP */] = "Firebase App named '{$appName}' already exists with different options or config", + _a["app-deleted" /* AppError.APP_DELETED */] = "Firebase App named '{$appName}' already deleted", + _a["server-app-deleted" /* AppError.SERVER_APP_DELETED */] = 'Firebase Server App has been deleted', + _a["no-options" /* AppError.NO_OPTIONS */] = 'Need to provide options, when not being deployed to hosting via source.', + _a["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */] = 'firebase.{$appName}() takes either no argument or a ' + + 'Firebase App instance.', + _a["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */] = 'First argument to `onLog` must be null or a function.', + _a["idb-open" /* AppError.IDB_OPEN */] = 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.', + _a["idb-get" /* AppError.IDB_GET */] = 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.', + _a["idb-set" /* AppError.IDB_WRITE */] = 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.', + _a["idb-delete" /* AppError.IDB_DELETE */] = 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.', + _a["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */] = 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.', + _a["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */] = 'FirebaseServerApp is not for use in browser environments.', + _a); + var 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. + */ + var FirebaseAppImpl = /** @class */ (function () { + function FirebaseAppImpl(options, config, container) { + var _this = this; + this._isDeleted = false; + this._options = tslib.__assign({}, options); + this._config = tslib.__assign({}, config); + this._name = config.name; + this._automaticDataCollectionEnabled = + config.automaticDataCollectionEnabled; + this._container = container; + this.container.addComponent(new component.Component('app', function () { return _this; }, "PUBLIC" /* ComponentType.PUBLIC */)); + } + Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", { + get: function () { + this.checkDestroyed(); + return this._automaticDataCollectionEnabled; + }, + set: function (val) { + this.checkDestroyed(); + this._automaticDataCollectionEnabled = val; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "name", { + get: function () { + this.checkDestroyed(); + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "options", { + get: function () { + this.checkDestroyed(); + return this._options; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "config", { + get: function () { + this.checkDestroyed(); + return this._config; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "container", { + get: function () { + return this._container; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FirebaseAppImpl.prototype, "isDeleted", { + get: function () { + return this._isDeleted; + }, + set: function (val) { + this._isDeleted = val; + }, + enumerable: false, + configurable: true + }); + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + FirebaseAppImpl.prototype.checkDestroyed = function () { + if (this.isDeleted) { + throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name }); + } + }; + return FirebaseAppImpl; + }()); - /** - * @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$1 = version$2; - 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$1(options, existingApp.options) && - deepEqual$1(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$1.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$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$1(logLevel) { - index_cjs$1.setLogLevel(logLevel); - } + /** + * @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. + */ + var FirebaseServerAppImpl = /** @class */ (function (_super) { + tslib.__extends(FirebaseServerAppImpl, _super); + function FirebaseServerAppImpl(options, serverConfig, name, container) { + var _this = this; + // Build configuration parameters for the FirebaseAppImpl base class. + var automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined + ? serverConfig.automaticDataCollectionEnabled + : false; + // Create the FirebaseAppSettings object for the FirebaseAppImp constructor. + var config = { + name: name, + automaticDataCollectionEnabled: automaticDataCollectionEnabled + }; + if (options.apiKey !== undefined) { + // Construct the parent FirebaseAppImp object. + _this = _super.call(this, options, config, container) || this; + } + else { + var appImpl = options; + _this = _super.call(this, appImpl.options, config, container) || this; + } + // Now construct the data for the FirebaseServerAppImpl. + _this._serverConfig = tslib.__assign({ automaticDataCollectionEnabled: automaticDataCollectionEnabled }, serverConfig); + _this._finalizationRegistry = null; + if (typeof FinalizationRegistry !== 'undefined') { + _this._finalizationRegistry = new FinalizationRegistry(function () { + _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$p, version$1, 'serverapp'); + return _this; + } + FirebaseServerAppImpl.prototype.toJSON = function () { + return undefined; + }; + Object.defineProperty(FirebaseServerAppImpl.prototype, "refCount", { + get: function () { + return this._refCount; + }, + enumerable: false, + configurable: true + }); + // Increment the reference count of this server app. If an object is provided, register it + // with the finalization registry. + FirebaseServerAppImpl.prototype.incRefCount = function (obj) { + if (this.isDeleted) { + return; + } + this._refCount++; + if (obj !== undefined && this._finalizationRegistry !== null) { + this._finalizationRegistry.register(obj, this); + } + }; + // Decrement the reference count. + FirebaseServerAppImpl.prototype.decRefCount = function () { + 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(...). + FirebaseServerAppImpl.prototype.automaticCleanup = function () { + void deleteApp(this); + }; + Object.defineProperty(FirebaseServerAppImpl.prototype, "settings", { + get: function () { + this.checkDestroyed(); + return this._serverConfig; + }, + enumerable: false, + configurable: true + }); + /** + * This function will throw an Error if the App has already been deleted - + * use before performing API actions on the App. + */ + FirebaseServerAppImpl.prototype.checkDestroyed = function () { + if (this.isDeleted) { + throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */); + } + }; + return FirebaseServerAppImpl; + }(FirebaseAppImpl)); - /** - * @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_1(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$1.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$1.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$1.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$1.warn(idbGetError.message); - } - } - } - function computeKey(app) { - return `${app.name}!${app.options.appId}`; - } + /** + * @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 + */ + var SDK_VERSION = version; + function initializeApp(_options, rawConfig) { + var e_1, _a; + if (rawConfig === void 0) { rawConfig = {}; } + var options = _options; + if (typeof rawConfig !== 'object') { + var name_1 = rawConfig; + rawConfig = { name: name_1 }; + } + var config = tslib.__assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig); + var 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 */); + } + var 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 }); + } + } + var container = new component.ComponentContainer(name); + try { + for (var _b = tslib.__values(_components.values()), _c = _b.next(); !_c.done; _c = _b.next()) { + var component$1 = _c.value; + container.addComponent(component$1); + } + } + 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; } + } + var newApp = new FirebaseAppImpl(options, config, container); + _apps.set(name, newApp); + return newApp; + } + function initializeServerApp(_options, _serverAppConfig) { + var e_2, _a; + 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; + } + var appOptions; + if (_isFirebaseApp(_options)) { + appOptions = _options.options; + } + else { + appOptions = _options; + } + // Build an app name based on a hash of the configuration options. + var nameObj = tslib.__assign(tslib.__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; + } + var hashCode = function (s) { + return tslib.__spreadArray([], tslib.__read(s), false).reduce(function (hash, c) { return (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 */, {}); + } + } + var nameString = '' + hashCode(JSON.stringify(nameObj)); + var existingApp = _serverApps.get(nameString); + if (existingApp) { + existingApp.incRefCount(_serverAppConfig.releaseOnDeref); + return existingApp; + } + var container = new component.ComponentContainer(nameString); + try { + for (var _b = tslib.__values(_components.values()), _c = _b.next(); !_c.done; _c = _b.next()) { + var component$1 = _c.value; + container.addComponent(component$1); + } + } + 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; } + } + var 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) { + if (name === void 0) { name = DEFAULT_ENTRY_NAME; } + var 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 + */ + function deleteApp(app) { + return tslib.__awaiter(this, void 0, void 0, function () { + var cleanupProviders, name, firebaseServerApp; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + cleanupProviders = false; + name = app.name; + if (_apps.has(name)) { + cleanupProviders = true; + _apps.delete(name); + } + else if (_serverApps.has(name)) { + firebaseServerApp = app; + if (firebaseServerApp.decRefCount() <= 0) { + _serverApps.delete(name); + cleanupProviders = true; + } + } + if (!cleanupProviders) return [3 /*break*/, 2]; + return [4 /*yield*/, Promise.all(app.container + .getProviders() + .map(function (provider) { return provider.delete(); }))]; + case 1: + _a.sent(); + app.isDeleted = true; + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + } + /** + * 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. + var library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName; + if (variant) { + library += "-".concat(variant); + } + var libraryMismatch = library.match(/\s|\//); + var versionMismatch = version.match(/\s|\//); + if (libraryMismatch || versionMismatch) { + var warning = [ + "Unable to register library \"".concat(library, "\" with version \"").concat(version, "\":") + ]; + if (libraryMismatch) { + warning.push("library name \"".concat(library, "\" contains illegal characters (whitespace or \"/\")")); + } + if (libraryMismatch && versionMismatch) { + warning.push('and'); + } + if (versionMismatch) { + warning.push("version name \"".concat(version, "\" contains illegal characters (whitespace or \"/\")")); + } + logger.warn(warning.join(' ')); + return; + } + _registerComponent(new component.Component("".concat(library, "-version"), function () { return ({ library: library, version: 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 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$1.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$1.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 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. + */ + var DB_NAME = 'firebase-heartbeat-database'; + var DB_VERSION = 1; + var STORE_NAME = 'firebase-heartbeat-store'; + var dbPromise = null; + function getDbPromise() { + if (!dbPromise) { + dbPromise = idb.openDB(DB_NAME, DB_VERSION, { + upgrade: function (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(function (e) { + throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, { + originalErrorMessage: e.message + }); + }); + } + return dbPromise; + } + function readHeartbeatsFromIndexedDB(app) { + return tslib.__awaiter(this, void 0, void 0, function () { + var db, tx, result, e_1, idbGetError; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 4, , 5]); + return [4 /*yield*/, getDbPromise()]; + case 1: + db = _a.sent(); + tx = db.transaction(STORE_NAME); + return [4 /*yield*/, tx.objectStore(STORE_NAME).get(computeKey(app))]; + case 2: + result = _a.sent(); + // We already have the value but tx.done can throw, + // so we need to await it here to catch errors + return [4 /*yield*/, tx.done]; + case 3: + // We already have the value but tx.done can throw, + // so we need to await it here to catch errors + _a.sent(); + return [2 /*return*/, result]; + case 4: + e_1 = _a.sent(); + if (e_1 instanceof util.FirebaseError) { + logger.warn(e_1.message); + } + else { + idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, { + originalErrorMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message + }); + logger.warn(idbGetError.message); + } + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); + } + function writeHeartbeatsToIndexedDB(app, heartbeatObject) { + return tslib.__awaiter(this, void 0, void 0, function () { + var db, tx, objectStore, e_2, idbGetError; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 4, , 5]); + return [4 /*yield*/, getDbPromise()]; + case 1: + db = _a.sent(); + tx = db.transaction(STORE_NAME, 'readwrite'); + objectStore = tx.objectStore(STORE_NAME); + return [4 /*yield*/, objectStore.put(heartbeatObject, computeKey(app))]; + case 2: + _a.sent(); + return [4 /*yield*/, tx.done]; + case 3: + _a.sent(); + return [3 /*break*/, 5]; + case 4: + e_2 = _a.sent(); + if (e_2 instanceof util.FirebaseError) { + logger.warn(e_2.message); + } + else { + idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, { + originalErrorMessage: e_2 === null || e_2 === void 0 ? void 0 : e_2.message + }); + logger.warn(idbGetError.message); + } + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); + } + function computeKey(app) { + return "".concat(app.name, "!").concat(app.options.appId); + } - /** - * @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$p, version$1$1, variant); - // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation - registerVersion(name$p, version$1$1, 'esm2017'); - // Register platform SDK identifier (no version). - registerVersion('fire-js', ''); - } + /** + * @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. + */ + var MAX_HEADER_BYTES = 1024; + // 30 days + var STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000; + var HeartbeatServiceImpl = /** @class */ (function () { + function HeartbeatServiceImpl(container) { + var _this = this; + 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; + var app = this.container.getProvider('app').getImmediate(); + this._storage = new HeartbeatStorageImpl(app); + this._heartbeatsCachePromise = this._storage.read().then(function (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. + */ + HeartbeatServiceImpl.prototype.triggerHeartbeat = function () { + var _a, _b; + return tslib.__awaiter(this, void 0, void 0, function () { + var platformLogger, agent, date_1, _c, e_1; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 3, , 4]); + platformLogger = this.container + .getProvider('platform-logger') + .getImmediate(); + agent = platformLogger.getPlatformInfoString(); + date_1 = getUTCDateString(); + if (!(((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null)) return [3 /*break*/, 2]; + _c = this; + return [4 /*yield*/, this._heartbeatsCachePromise]; + case 1: + _c._heartbeatsCache = _d.sent(); + // 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 [2 /*return*/]; + } + _d.label = 2; + case 2: + // 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_1 || + this._heartbeatsCache.heartbeats.some(function (singleDateHeartbeat) { return singleDateHeartbeat.date === date_1; })) { + return [2 /*return*/]; + } + else { + // There is no entry for this date. Create one. + this._heartbeatsCache.heartbeats.push({ date: date_1, agent: agent }); + } + // Remove entries older than 30 days. + this._heartbeatsCache.heartbeats = + this._heartbeatsCache.heartbeats.filter(function (singleDateHeartbeat) { + var hbTimestamp = new Date(singleDateHeartbeat.date).valueOf(); + var now = Date.now(); + return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS; + }); + return [2 /*return*/, this._storage.overwrite(this._heartbeatsCache)]; + case 3: + e_1 = _d.sent(); + logger.warn(e_1); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + /** + * 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. + */ + HeartbeatServiceImpl.prototype.getHeartbeatsHeader = function () { + var _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var date, _b, heartbeatsToSend, unsentEntries, headerString, e_2; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, 6, , 7]); + if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2]; + return [4 /*yield*/, this._heartbeatsCachePromise]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + // 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 [2 /*return*/, '']; + } + date = getUTCDateString(); + _b = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats), heartbeatsToSend = _b.heartbeatsToSend, unsentEntries = _b.unsentEntries; + 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)) return [3 /*break*/, 4]; + // 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. + return [4 /*yield*/, this._storage.overwrite(this._heartbeatsCache)]; + case 3: + // 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. + _c.sent(); + return [3 /*break*/, 5]; + case 4: + this._heartbeatsCache.heartbeats = []; + // Do not wait for this, to reduce latency. + void this._storage.overwrite(this._heartbeatsCache); + _c.label = 5; + case 5: return [2 /*return*/, headerString]; + case 6: + e_2 = _c.sent(); + logger.warn(e_2); + return [2 /*return*/, '']; + case 7: return [2 /*return*/]; + } + }); + }); + }; + return HeartbeatServiceImpl; + }()); + function getUTCDateString() { + var today = new Date(); + // Returns date format 'YYYY-MM-DD' + return today.toISOString().substring(0, 10); + } + function extractHeartbeatsForHeader(heartbeatsCache, maxSize) { + var e_3, _a; + if (maxSize === void 0) { maxSize = MAX_HEADER_BYTES; } + // Heartbeats grouped by user agent in the standard format to be sent in + // the header. + var heartbeatsToSend = []; + // Single date format heartbeats that are not sent. + var unsentEntries = heartbeatsCache.slice(); + var _loop_1 = function (singleDateHeartbeat) { + // Look for an existing entry with the same user agent. + var heartbeatEntry = heartbeatsToSend.find(function (hb) { return 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(); + return "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(); + return "break"; + } + } + // Pop unsent entry from queue. (Skipped if adding the entry exceeded + // quota and the loop breaks early.) + unsentEntries = unsentEntries.slice(1); + }; + try { + for (var heartbeatsCache_1 = tslib.__values(heartbeatsCache), heartbeatsCache_1_1 = heartbeatsCache_1.next(); !heartbeatsCache_1_1.done; heartbeatsCache_1_1 = heartbeatsCache_1.next()) { + var singleDateHeartbeat = heartbeatsCache_1_1.value; + var state_1 = _loop_1(singleDateHeartbeat); + if (state_1 === "break") + break; + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (heartbeatsCache_1_1 && !heartbeatsCache_1_1.done && (_a = heartbeatsCache_1.return)) _a.call(heartbeatsCache_1); + } + finally { if (e_3) throw e_3.error; } + } + return { + heartbeatsToSend: heartbeatsToSend, + unsentEntries: unsentEntries + }; + } + var HeartbeatStorageImpl = /** @class */ (function () { + function HeartbeatStorageImpl(app) { + this.app = app; + this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck(); + } + HeartbeatStorageImpl.prototype.runIndexedDBEnvironmentCheck = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + if (!util.isIndexedDBAvailable()) { + return [2 /*return*/, false]; + } + else { + return [2 /*return*/, util.validateIndexedDBOpenable() + .then(function () { return true; }) + .catch(function () { return false; })]; + } + }); + }); + }; + /** + * Read all heartbeats. + */ + HeartbeatStorageImpl.prototype.read = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var canUseIndexedDB, idbHeartbeatObject; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this._canUseIndexedDBPromise]; + case 1: + canUseIndexedDB = _a.sent(); + if (!!canUseIndexedDB) return [3 /*break*/, 2]; + return [2 /*return*/, { heartbeats: [] }]; + case 2: return [4 /*yield*/, readHeartbeatsFromIndexedDB(this.app)]; + case 3: + idbHeartbeatObject = _a.sent(); + if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) { + return [2 /*return*/, idbHeartbeatObject]; + } + else { + return [2 /*return*/, { heartbeats: [] }]; + } + case 4: return [2 /*return*/]; + } + }); + }); + }; + // overwrite the storage with the provided heartbeats + HeartbeatStorageImpl.prototype.overwrite = function (heartbeatsObject) { + var _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var canUseIndexedDB, existingHeartbeatsObject; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this._canUseIndexedDBPromise]; + case 1: + canUseIndexedDB = _b.sent(); + if (!!canUseIndexedDB) return [3 /*break*/, 2]; + return [2 /*return*/]; + case 2: return [4 /*yield*/, this.read()]; + case 3: + existingHeartbeatsObject = _b.sent(); + return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: heartbeatsObject.heartbeats + })]; + } + }); + }); + }; + // add heartbeats + HeartbeatStorageImpl.prototype.add = function (heartbeatsObject) { + var _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var canUseIndexedDB, existingHeartbeatsObject; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this._canUseIndexedDBPromise]; + case 1: + canUseIndexedDB = _b.sent(); + if (!!canUseIndexedDB) return [3 /*break*/, 2]; + return [2 /*return*/]; + case 2: return [4 /*yield*/, this.read()]; + case 3: + existingHeartbeatsObject = _b.sent(); + return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, { + lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate, + heartbeats: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(existingHeartbeatsObject.heartbeats), false), tslib.__read(heartbeatsObject.heartbeats), false) + })]; + } + }); + }); + }; + return HeartbeatStorageImpl; + }()); + /** + * 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; + } - /** - * Firebase App - * - * @remarks This package coordinates the communication between the different Firebase components - * @packageDocumentation - */ - registerCoreComponents(''); + /** + * @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', function (container) { return new PlatformLoggerServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */)); + _registerComponent(new component.Component('heartbeat', function (container) { return new HeartbeatServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */)); + // Register `app` package. + registerVersion(name$p, version$1, variant); + // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation + registerVersion(name$p, version$1, 'cjs5'); + // Register platform SDK identifier (no version). + registerVersion('fire-js', ''); + } - var index_esm2017 = /*#__PURE__*/Object.freeze({ - __proto__: null, - FirebaseError: FirebaseError, - SDK_VERSION: SDK_VERSION$1, - _DEFAULT_ENTRY_NAME: DEFAULT_ENTRY_NAME, - _addComponent: _addComponent, - _addOrOverwriteComponent: _addOrOverwriteComponent, - _apps: _apps, - _clearComponents: _clearComponents, - _components: _components, - _getProvider: _getProvider, - _isFirebaseApp: _isFirebaseApp, - _isFirebaseServerApp: _isFirebaseServerApp, - _registerComponent: _registerComponent, - _removeServiceInstance: _removeServiceInstance, - _serverApps: _serverApps, - deleteApp: deleteApp, - getApp: getApp, - getApps: getApps, - initializeApp: initializeApp, - initializeServerApp: initializeServerApp, - onLog: onLog, - registerVersion: registerVersion, - setLogLevel: setLogLevel$1 - }); + /** + * Firebase App + * + * @remarks This package coordinates the communication between the different Firebase components + * @packageDocumentation + */ + registerCoreComponents('node'); - var require$$0$3 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); + 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$3)); (function (exports) { Object.defineProperty(exports, '__esModule', { value: true }); - var app = require$$0$3; + var app = index_cjs$3; var name = "firebase"; var version = "10.13.1"; @@ -4112,7 +4374,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); }); - } (index_cjs$2)); + } (index_cjs$4)); var index_cjs = {}; @@ -6061,8 +6323,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; var index_node_cjs = {}; - var require$$1$5 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$1); - var inherits; if (typeof Object.create === 'function'){ inherits = function inherits(ctor, superCtor) { @@ -6802,8 +7062,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; var require$$3$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util); - var require$$4$1 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$2); - var undici$1 = {}; function compare(a, b) { @@ -43520,11 +43778,11 @@ ${pendingInterceptorsFormatter.format(pending)} Object.defineProperty(index_node_cjs, '__esModule', { value: true }); - var app = require$$0$3; - var component = require$$1$5; + var app = index_cjs$3; + var component = index_cjs$2; var logger = index_cjs$1; var util$1 = require$$3$1; - var util = require$$4$1; + var util = require$$4$2; var undici = undici$1; var crypto = require$$6; @@ -53041,6 +53299,6 @@ ${pendingInterceptorsFormatter.format(pending)} exports.doc = index_cjs.doc; exports.getDoc = index_cjs.getDoc; exports.getFirestore = index_cjs.getFirestore; - exports.initializeApp = index_cjs$2.initializeApp; + exports.initializeApp = index_cjs$4.initializeApp; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/95c13606/_chunks_/jspdf.es.min2.js b/packages/ui5-tooling-modules/test/__snap__/95c13606/_chunks_/jspdf.es.min2.js index 75a3f90ce..e6c098037 100644 --- a/packages/ui5-tooling-modules/test/__snap__/95c13606/_chunks_/jspdf.es.min2.js +++ b/packages/ui5-tooling-modules/test/__snap__/95c13606/_chunks_/jspdf.es.min2.js @@ -30,13 +30,6 @@ sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict // Many optimizations have been made, so the bundle size is ultimately smaller but performance is similar. // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint // is better for memory in most engines (I *think*). - // Mediocre shim - var Worker; - try { - Worker = require('worker_threads').Worker; - } - catch (e) { - } // aliases for shorter compressed code (most minifers don't do this) var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array; @@ -987,7 +980,7 @@ sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ - function(t){function e(){return (n.canvg?Promise.resolve(n.canvg):new Promise(function (resolve, reject) { require(['ui5/ecosystem/demo/tsapp/resources/_chunks_/index'], resolve, reject); }).then(function (n) { return n.index; })).catch((function(t){return Promise.reject(new Error("Could not load canvg: "+t))})).then((function(t){return t.default?t.default:t}))}E.API.addSvgAsImage=function(t,r,n,i,o,s,c,u){if(isNaN(r)||isNaN(n))throw a.error("jsPDF.addSvgAsImage: Invalid coordinates",arguments),new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");if(isNaN(i)||isNaN(o))throw a.error("jsPDF.addSvgAsImage: Invalid measurements",arguments),new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage");var h=document.createElement("canvas");h.width=i,h.height=o;var l=h.getContext("2d");l.fillStyle="#fff",l.fillRect(0,0,h.width,h.height);var f={ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0},d=this;return e().then((function(e){return e.fromString(l,t,f)}),(function(){return Promise.reject(new Error("Could not load canvg."))})).then((function(t){return t.render(f)})).then((function(){d.addImage(h.toDataURL("image/jpeg",1),r,n,i,o,c,u);}))};}(),E.API.putTotalPages=function(t){var e,r=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(e=new RegExp(t,"g"),r=this.internal.getNumberOfPages()):(e=new RegExp(this.pdfEscape16(t,this.internal.getFont()),"g"),r=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var n=1;n<=this.internal.getNumberOfPages();n++)for(var i=0;i1){for(l=0;l>");})),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this}, + function(t){function e(){return (n.canvg?Promise.resolve(n.canvg):new Promise(function (resolve, reject) { require(['ui5/ecosystem/demo/tsapp/resources/_chunks_/index.es'], resolve, reject); })).catch((function(t){return Promise.reject(new Error("Could not load canvg: "+t))})).then((function(t){return t.default?t.default:t}))}E.API.addSvgAsImage=function(t,r,n,i,o,s,c,u){if(isNaN(r)||isNaN(n))throw a.error("jsPDF.addSvgAsImage: Invalid coordinates",arguments),new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");if(isNaN(i)||isNaN(o))throw a.error("jsPDF.addSvgAsImage: Invalid measurements",arguments),new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage");var h=document.createElement("canvas");h.width=i,h.height=o;var l=h.getContext("2d");l.fillStyle="#fff",l.fillRect(0,0,h.width,h.height);var f={ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0},d=this;return e().then((function(e){return e.fromString(l,t,f)}),(function(){return Promise.reject(new Error("Could not load canvg."))})).then((function(t){return t.render(f)})).then((function(){d.addImage(h.toDataURL("image/jpeg",1),r,n,i,o,c,u);}))};}(),E.API.putTotalPages=function(t){var e,r=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(e=new RegExp(t,"g"),r=this.internal.getNumberOfPages()):(e=new RegExp(this.pdfEscape16(t,this.internal.getFont()),"g"),r=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var n=1;n<=this.internal.getNumberOfPages();n++)for(var i=0;i1){for(l=0;l>");})),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this}, /** ==================================================================== * @license * jsPDF XMP metadata plugin diff --git a/packages/ui5-tooling-modules/test/__snap__/a230bdfe/@supabase/supabase-js.js b/packages/ui5-tooling-modules/test/__snap__/a230bdfe/@supabase/supabase-js.js index 05c9e8bc3..6cbb26ea2 100644 --- a/packages/ui5-tooling-modules/test/__snap__/a230bdfe/@supabase/supabase-js.js +++ b/packages/ui5-tooling-modules/test/__snap__/a230bdfe/@supabase/supabase-js.js @@ -1,9163 +1,60 @@ -sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict'; - - const resolveFetch$3 = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - - class FunctionsError extends Error { - constructor(message, name = 'FunctionsError', context) { - super(message); - this.name = name; - this.context = context; - } - } - class FunctionsFetchError extends FunctionsError { - constructor(context) { - super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); - } - } - class FunctionsRelayError extends FunctionsError { - constructor(context) { - super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); - } - } - class FunctionsHttpError extends FunctionsError { - constructor(context) { - super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); - } - } - // Define the enum for the 'region' property - exports.FunctionRegion = void 0; - (function (FunctionRegion) { - FunctionRegion["Any"] = "any"; - FunctionRegion["ApNortheast1"] = "ap-northeast-1"; - FunctionRegion["ApNortheast2"] = "ap-northeast-2"; - FunctionRegion["ApSouth1"] = "ap-south-1"; - FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; - FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; - FunctionRegion["CaCentral1"] = "ca-central-1"; - FunctionRegion["EuCentral1"] = "eu-central-1"; - FunctionRegion["EuWest1"] = "eu-west-1"; - FunctionRegion["EuWest2"] = "eu-west-2"; - FunctionRegion["EuWest3"] = "eu-west-3"; - FunctionRegion["SaEast1"] = "sa-east-1"; - FunctionRegion["UsEast1"] = "us-east-1"; - FunctionRegion["UsWest1"] = "us-west-1"; - FunctionRegion["UsWest2"] = "us-west-2"; - })(exports.FunctionRegion || (exports.FunctionRegion = {})); - - var __awaiter$7 = (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()); - }); - }; - class FunctionsClient { - constructor(url, { headers = {}, customFetch, region = exports.FunctionRegion.Any, } = {}) { - this.url = url; - this.headers = headers; - this.region = region; - this.fetch = resolveFetch$3(customFetch); - } - /** - * Updates the authorization header - * @param token - the new jwt token sent in the authorisation header - */ - setAuth(token) { - this.headers.Authorization = `Bearer ${token}`; - } - /** - * Invokes a function - * @param functionName - The name of the Function to invoke. - * @param options - Options for invoking the Function. - */ - invoke(functionName, options = {}) { - var _a; - return __awaiter$7(this, void 0, void 0, function* () { - try { - const { headers, method, body: functionArgs } = options; - let _headers = {}; - let { region } = options; - if (!region) { - region = this.region; - } - if (region && region !== 'any') { - _headers['x-region'] = region; - } - let body; - if (functionArgs && - ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { - if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || - functionArgs instanceof ArrayBuffer) { - // will work for File as File inherits Blob - // also works for ArrayBuffer as it is the same underlying structure as a Blob - _headers['Content-Type'] = 'application/octet-stream'; - body = functionArgs; - } - else if (typeof functionArgs === 'string') { - // plain string - _headers['Content-Type'] = 'text/plain'; - body = functionArgs; - } - else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { - // don't set content-type headers - // Request will automatically add the right boundary value - body = functionArgs; - } - else { - // default, assume this is JSON - _headers['Content-Type'] = 'application/json'; - body = JSON.stringify(functionArgs); - } - } - const response = yield this.fetch(`${this.url}/${functionName}`, { - method: method || 'POST', - // headers priority is (high to low): - // 1. invoke-level headers - // 2. client-level headers - // 3. default Content-Type header - headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), - body, - }).catch((fetchError) => { - throw new FunctionsFetchError(fetchError); - }); - const isRelayError = response.headers.get('x-relay-error'); - if (isRelayError && isRelayError === 'true') { - throw new FunctionsRelayError(response); - } - if (!response.ok) { - throw new FunctionsHttpError(response); - } - let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); - let data; - if (responseType === 'application/json') { - data = yield response.json(); - } - else if (responseType === 'application/octet-stream') { - data = yield response.blob(); - } - else if (responseType === 'text/event-stream') { - data = response; - } - else if (responseType === 'multipart/form-data') { - data = yield response.formData(); - } - else { - // default to text - data = yield response.text(); - } - return { data, error: null }; - } - catch (error) { - return { data: null, error }; - } - }); - } - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - 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 cjs = {}; - - var PostgrestClient$2 = {}; - - var PostgrestQueryBuilder$1 = {}; - - var PostgrestFilterBuilder$1 = {}; - - var PostgrestTransformBuilder$1 = {}; - - var PostgrestBuilder$1 = {}; - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - // ref: https://github.com/tc39/proposal-global - var getGlobal = function() { - // the only reliable means to get the global object is - // `Function('return this')()` - // However, this causes CSP violations in Chrome apps. - 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'); - }; - - var globalObject = getGlobal(); - - const fetch$1 = globalObject.fetch; - - var nodeFetch = globalObject.fetch.bind(globalObject); - - const Headers$1 = globalObject.Headers; - const Request = globalObject.Request; - const Response$1 = globalObject.Response; - - var browser = /*#__PURE__*/Object.freeze({ - __proto__: null, - Headers: Headers$1, - Request: Request, - Response: Response$1, - default: nodeFetch, - fetch: fetch$1 - }); - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(browser); - - var PostgrestError$1 = {}; - - Object.defineProperty(PostgrestError$1, "__esModule", { value: true }); - class PostgrestError extends Error { - constructor(context) { - super(context.message); - this.name = 'PostgrestError'; - this.details = context.details; - this.hint = context.hint; - this.code = context.code; - } - } - PostgrestError$1.default = PostgrestError; - - var __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(PostgrestBuilder$1, "__esModule", { value: true }); - // @ts-ignore - const node_fetch_1 = __importDefault$5(require$$0); - const PostgrestError_1 = __importDefault$5(PostgrestError$1); - class PostgrestBuilder { - constructor(builder) { - this.shouldThrowOnError = false; - this.method = builder.method; - this.url = builder.url; - this.headers = builder.headers; - this.schema = builder.schema; - this.body = builder.body; - this.shouldThrowOnError = builder.shouldThrowOnError; - this.signal = builder.signal; - this.isMaybeSingle = builder.isMaybeSingle; - if (builder.fetch) { - this.fetch = builder.fetch; - } - else if (typeof fetch === 'undefined') { - this.fetch = node_fetch_1.default; - } - else { - this.fetch = fetch; - } - } - /** - * If there's an error with the query, throwOnError will reject the promise by - * throwing the error instead of returning it as part of a successful response. - * - * {@link https://github.com/supabase/supabase-js/issues/92} - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - then(onfulfilled, onrejected) { - // https://postgrest.org/en/stable/api.html#switching-schemas - if (this.schema === undefined) ; - else if (['GET', 'HEAD'].includes(this.method)) { - this.headers['Accept-Profile'] = this.schema; - } - else { - this.headers['Content-Profile'] = this.schema; - } - if (this.method !== 'GET' && this.method !== 'HEAD') { - this.headers['Content-Type'] = 'application/json'; - } - // NOTE: Invoke w/o `this` to avoid illegal invocation error. - // https://github.com/supabase/postgrest-js/pull/247 - const _fetch = this.fetch; - let res = _fetch(this.url.toString(), { - method: this.method, - headers: this.headers, - body: JSON.stringify(this.body), - signal: this.signal, - }).then(async (res) => { - var _a, _b, _c; - let error = null; - let data = null; - let count = null; - let status = res.status; - let statusText = res.statusText; - if (res.ok) { - if (this.method !== 'HEAD') { - const body = await res.text(); - if (body === '') ; - else if (this.headers['Accept'] === 'text/csv') { - data = body; - } - else if (this.headers['Accept'] && - this.headers['Accept'].includes('application/vnd.pgrst.plan+text')) { - data = body; - } - else { - data = JSON.parse(body); - } - } - const countHeader = (_a = this.headers['Prefer']) === null || _a === void 0 ? void 0 : _a.match(/count=(exact|planned|estimated)/); - const contentRange = (_b = res.headers.get('content-range')) === null || _b === void 0 ? void 0 : _b.split('/'); - if (countHeader && contentRange && contentRange.length > 1) { - count = parseInt(contentRange[1]); - } - // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 - // Issue persists e.g. for `.insert([...]).select().maybeSingle()` - if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { - if (data.length > 1) { - error = { - // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 - code: 'PGRST116', - details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, - hint: null, - message: 'JSON object requested, multiple (or no) rows returned', - }; - data = null; - count = null; - status = 406; - statusText = 'Not Acceptable'; - } - else if (data.length === 1) { - data = data[0]; - } - else { - data = null; - } - } - } - else { - const body = await res.text(); - try { - error = JSON.parse(body); - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (Array.isArray(error) && res.status === 404) { - data = []; - error = null; - status = 200; - statusText = 'OK'; - } - } - catch (_d) { - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (res.status === 404 && body === '') { - status = 204; - statusText = 'No Content'; - } - else { - error = { - message: body, - }; - } - } - if (error && this.isMaybeSingle && ((_c = error === null || error === void 0 ? void 0 : error.details) === null || _c === void 0 ? void 0 : _c.includes('0 rows'))) { - error = null; - status = 200; - statusText = 'OK'; - } - if (error && this.shouldThrowOnError) { - throw new PostgrestError_1.default(error); - } - } - const postgrestResponse = { - error, - data, - count, - status, - statusText, - }; - return postgrestResponse; - }); - if (!this.shouldThrowOnError) { - res = res.catch((fetchError) => { - var _a, _b, _c; - return ({ - error: { - message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, - details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, - hint: '', - code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, - }, - data: null, - count: null, - status: 0, - statusText: '', - }); - }); - } - return res.then(onfulfilled, onrejected); - } - } - PostgrestBuilder$1.default = PostgrestBuilder; - - var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(PostgrestTransformBuilder$1, "__esModule", { value: true }); - const PostgrestBuilder_1$1 = __importDefault$4(PostgrestBuilder$1); - class PostgrestTransformBuilder extends PostgrestBuilder_1$1.default { - /** - * Perform a SELECT on the query result. - * - * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not - * return modified rows. By calling this method, modified rows are returned in - * `data`. - * - * @param columns - The columns to retrieve, separated by commas - */ - select(columns) { - // Remove whitespaces except when quoted - let quoted = false; - const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') - .split('') - .map((c) => { - if (/\s/.test(c) && !quoted) { - return ''; - } - if (c === '"') { - quoted = !quoted; - } - return c; - }) - .join(''); - this.url.searchParams.set('select', cleanedColumns); - if (this.headers['Prefer']) { - this.headers['Prefer'] += ','; - } - this.headers['Prefer'] += 'return=representation'; - return this; - } - /** - * Order the query result by `column`. - * - * You can call this method multiple times to order by multiple columns. - * - * You can order referenced tables, but it only affects the ordering of the - * parent table if you use `!inner` in the query. - * - * @param column - The column to order by - * @param options - Named parameters - * @param options.ascending - If `true`, the result will be in ascending order - * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, - * `null`s appear last. - * @param options.referencedTable - Set this to order a referenced table by - * its columns - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { - const key = referencedTable ? `${referencedTable}.order` : 'order'; - const existingOrder = this.url.searchParams.get(key); - this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); - return this; - } - /** - * Limit the query result by `count`. - * - * @param count - The maximum number of rows to return - * @param options - Named parameters - * @param options.referencedTable - Set this to limit rows of referenced - * tables instead of the parent table - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { - const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; - this.url.searchParams.set(key, `${count}`); - return this; - } - /** - * Limit the query result by starting at an offset `from` and ending at the offset `to`. - * Only records within this range are returned. - * This respects the query order and if there is no order clause the range could behave unexpectedly. - * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third - * and fourth rows of the query. - * - * @param from - The starting index from which to limit the result - * @param to - The last index to which to limit the result - * @param options - Named parameters - * @param options.referencedTable - Set this to limit rows of referenced - * tables instead of the parent table - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { - const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; - const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; - this.url.searchParams.set(keyOffset, `${from}`); - // Range is inclusive, so add 1 - this.url.searchParams.set(keyLimit, `${to - from + 1}`); - return this; - } - /** - * Set the AbortSignal for the fetch request. - * - * @param signal - The AbortSignal to use for the fetch request - */ - abortSignal(signal) { - this.signal = signal; - return this; - } - /** - * Return `data` as a single object instead of an array of objects. - * - * Query result must be one row (e.g. using `.limit(1)`), otherwise this - * returns an error. - */ - single() { - this.headers['Accept'] = 'application/vnd.pgrst.object+json'; - return this; - } - /** - * Return `data` as a single object instead of an array of objects. - * - * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise - * this returns an error. - */ - maybeSingle() { - // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 - // Issue persists e.g. for `.insert([...]).select().maybeSingle()` - if (this.method === 'GET') { - this.headers['Accept'] = 'application/json'; - } - else { - this.headers['Accept'] = 'application/vnd.pgrst.object+json'; - } - this.isMaybeSingle = true; - return this; - } - /** - * Return `data` as a string in CSV format. - */ - csv() { - this.headers['Accept'] = 'text/csv'; - return this; - } - /** - * Return `data` as an object in [GeoJSON](https://geojson.org) format. - */ - geojson() { - this.headers['Accept'] = 'application/geo+json'; - return this; - } - /** - * Return `data` as the EXPLAIN plan for the query. - * - * You need to enable the - * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) - * setting before using this method. - * - * @param options - Named parameters - * - * @param options.analyze - If `true`, the query will be executed and the - * actual run time will be returned - * - * @param options.verbose - If `true`, the query identifier will be returned - * and `data` will include the output columns of the query - * - * @param options.settings - If `true`, include information on configuration - * parameters that affect query planning - * - * @param options.buffers - If `true`, include information on buffer usage - * - * @param options.wal - If `true`, include information on WAL record generation - * - * @param options.format - The format of the output, can be `"text"` (default) - * or `"json"` - */ - explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { - var _a; - const options = [ - analyze ? 'analyze' : null, - verbose ? 'verbose' : null, - settings ? 'settings' : null, - buffers ? 'buffers' : null, - wal ? 'wal' : null, - ] - .filter(Boolean) - .join('|'); - // An Accept header can carry multiple media types but postgrest-js always sends one - const forMediatype = (_a = this.headers['Accept']) !== null && _a !== void 0 ? _a : 'application/json'; - this.headers['Accept'] = `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`; - if (format === 'json') - return this; - else - return this; - } - /** - * Rollback the query. - * - * `data` will still be returned, but the query is not committed. - */ - rollback() { - var _a; - if (((_a = this.headers['Prefer']) !== null && _a !== void 0 ? _a : '').trim().length > 0) { - this.headers['Prefer'] += ',tx=rollback'; - } - else { - this.headers['Prefer'] = 'tx=rollback'; - } - return this; - } - /** - * Override the type of the returned `data`. - * - * @typeParam NewResult - The new result type to override with - */ - returns() { - return this; - } - } - PostgrestTransformBuilder$1.default = PostgrestTransformBuilder; - - var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(PostgrestFilterBuilder$1, "__esModule", { value: true }); - const PostgrestTransformBuilder_1$1 = __importDefault$3(PostgrestTransformBuilder$1); - class PostgrestFilterBuilder extends PostgrestTransformBuilder_1$1.default { - /** - * Match only rows where `column` is equal to `value`. - * - * To check if the value of `column` is NULL, you should use `.is()` instead. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - eq(column, value) { - this.url.searchParams.append(column, `eq.${value}`); - return this; - } - /** - * Match only rows where `column` is not equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - neq(column, value) { - this.url.searchParams.append(column, `neq.${value}`); - return this; - } - /** - * Match only rows where `column` is greater than `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - gt(column, value) { - this.url.searchParams.append(column, `gt.${value}`); - return this; - } - /** - * Match only rows where `column` is greater than or equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - gte(column, value) { - this.url.searchParams.append(column, `gte.${value}`); - return this; - } - /** - * Match only rows where `column` is less than `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - lt(column, value) { - this.url.searchParams.append(column, `lt.${value}`); - return this; - } - /** - * Match only rows where `column` is less than or equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - lte(column, value) { - this.url.searchParams.append(column, `lte.${value}`); - return this; - } - /** - * Match only rows where `column` matches `pattern` case-sensitively. - * - * @param column - The column to filter on - * @param pattern - The pattern to match with - */ - like(column, pattern) { - this.url.searchParams.append(column, `like.${pattern}`); - return this; - } - /** - * Match only rows where `column` matches all of `patterns` case-sensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - likeAllOf(column, patterns) { - this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches any of `patterns` case-sensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - likeAnyOf(column, patterns) { - this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches `pattern` case-insensitively. - * - * @param column - The column to filter on - * @param pattern - The pattern to match with - */ - ilike(column, pattern) { - this.url.searchParams.append(column, `ilike.${pattern}`); - return this; - } - /** - * Match only rows where `column` matches all of `patterns` case-insensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - ilikeAllOf(column, patterns) { - this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches any of `patterns` case-insensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - ilikeAnyOf(column, patterns) { - this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` IS `value`. - * - * For non-boolean columns, this is only relevant for checking if the value of - * `column` is NULL by setting `value` to `null`. - * - * For boolean columns, you can also set `value` to `true` or `false` and it - * will behave the same way as `.eq()`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - is(column, value) { - this.url.searchParams.append(column, `is.${value}`); - return this; - } - /** - * Match only rows where `column` is included in the `values` array. - * - * @param column - The column to filter on - * @param values - The values array to filter with - */ - in(column, values) { - const cleanedValues = Array.from(new Set(values)) - .map((s) => { - // handle postgrest reserved characters - // https://postgrest.org/en/v7.0.0/api.html#reserved-characters - if (typeof s === 'string' && new RegExp('[,()]').test(s)) - return `"${s}"`; - else - return `${s}`; - }) - .join(','); - this.url.searchParams.append(column, `in.(${cleanedValues})`); - return this; - } - /** - * Only relevant for jsonb, array, and range columns. Match only rows where - * `column` contains every element appearing in `value`. - * - * @param column - The jsonb, array, or range column to filter on - * @param value - The jsonb, array, or range value to filter with - */ - contains(column, value) { - if (typeof value === 'string') { - // range types can be inclusive '[', ']' or exclusive '(', ')' so just - // keep it simple and accept a string - this.url.searchParams.append(column, `cs.${value}`); - } - else if (Array.isArray(value)) { - // array - this.url.searchParams.append(column, `cs.{${value.join(',')}}`); - } - else { - // json - this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); - } - return this; - } - /** - * Only relevant for jsonb, array, and range columns. Match only rows where - * every element appearing in `column` is contained by `value`. - * - * @param column - The jsonb, array, or range column to filter on - * @param value - The jsonb, array, or range value to filter with - */ - containedBy(column, value) { - if (typeof value === 'string') { - // range - this.url.searchParams.append(column, `cd.${value}`); - } - else if (Array.isArray(value)) { - // array - this.url.searchParams.append(column, `cd.{${value.join(',')}}`); - } - else { - // json - this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); - } - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is greater than any element in `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeGt(column, range) { - this.url.searchParams.append(column, `sr.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is either contained in `range` or greater than any element in - * `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeGte(column, range) { - this.url.searchParams.append(column, `nxl.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is less than any element in `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeLt(column, range) { - this.url.searchParams.append(column, `sl.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is either contained in `range` or less than any element in - * `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeLte(column, range) { - this.url.searchParams.append(column, `nxr.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where `column` is - * mutually exclusive to `range` and there can be no element between the two - * ranges. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeAdjacent(column, range) { - this.url.searchParams.append(column, `adj.${range}`); - return this; - } - /** - * Only relevant for array and range columns. Match only rows where - * `column` and `value` have an element in common. - * - * @param column - The array or range column to filter on - * @param value - The array or range value to filter with - */ - overlaps(column, value) { - if (typeof value === 'string') { - // range - this.url.searchParams.append(column, `ov.${value}`); - } - else { - // array - this.url.searchParams.append(column, `ov.{${value.join(',')}}`); - } - return this; - } - /** - * Only relevant for text and tsvector columns. Match only rows where - * `column` matches the query string in `query`. - * - * @param column - The text or tsvector column to filter on - * @param query - The query text to match with - * @param options - Named parameters - * @param options.config - The text search configuration to use - * @param options.type - Change how the `query` text is interpreted - */ - textSearch(column, query, { config, type } = {}) { - let typePart = ''; - if (type === 'plain') { - typePart = 'pl'; - } - else if (type === 'phrase') { - typePart = 'ph'; - } - else if (type === 'websearch') { - typePart = 'w'; - } - const configPart = config === undefined ? '' : `(${config})`; - this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); - return this; - } - /** - * Match only rows where each column in `query` keys is equal to its - * associated value. Shorthand for multiple `.eq()`s. - * - * @param query - The object to filter with, with column names as keys mapped - * to their filter values - */ - match(query) { - Object.entries(query).forEach(([column, value]) => { - this.url.searchParams.append(column, `eq.${value}`); - }); - return this; - } - /** - * Match only rows which doesn't satisfy the filter. - * - * Unlike most filters, `opearator` and `value` are used as-is and need to - * follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure they are properly sanitized. - * - * @param column - The column to filter on - * @param operator - The operator to be negated to filter with, following - * PostgREST syntax - * @param value - The value to filter with, following PostgREST syntax - */ - not(column, operator, value) { - this.url.searchParams.append(column, `not.${operator}.${value}`); - return this; - } - /** - * Match only rows which satisfy at least one of the filters. - * - * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure it's properly sanitized. - * - * It's currently not possible to do an `.or()` filter across multiple tables. - * - * @param filters - The filters to use, following PostgREST syntax - * @param options - Named parameters - * @param options.referencedTable - Set this to filter on referenced tables - * instead of the parent table - * @param options.foreignTable - Deprecated, use `referencedTable` instead - */ - or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { - const key = referencedTable ? `${referencedTable}.or` : 'or'; - this.url.searchParams.append(key, `(${filters})`); - return this; - } - /** - * Match only rows which satisfy the filter. This is an escape hatch - you - * should use the specific filter methods wherever possible. - * - * Unlike most filters, `opearator` and `value` are used as-is and need to - * follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure they are properly sanitized. - * - * @param column - The column to filter on - * @param operator - The operator to filter with, following PostgREST syntax - * @param value - The value to filter with, following PostgREST syntax - */ - filter(column, operator, value) { - this.url.searchParams.append(column, `${operator}.${value}`); - return this; - } - } - PostgrestFilterBuilder$1.default = PostgrestFilterBuilder; - - var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(PostgrestQueryBuilder$1, "__esModule", { value: true }); - const PostgrestFilterBuilder_1$2 = __importDefault$2(PostgrestFilterBuilder$1); - class PostgrestQueryBuilder { - constructor(url, { headers = {}, schema, fetch, }) { - this.url = url; - this.headers = headers; - this.schema = schema; - this.fetch = fetch; - } - /** - * Perform a SELECT query on the table or view. - * - * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` - * - * @param options - Named parameters - * - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * - * @param options.count - Count algorithm to use to count rows in the table or view. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - select(columns, { head = false, count, } = {}) { - const method = head ? 'HEAD' : 'GET'; - // Remove whitespaces except when quoted - let quoted = false; - const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') - .split('') - .map((c) => { - if (/\s/.test(c) && !quoted) { - return ''; - } - if (c === '"') { - quoted = !quoted; - } - return c; - }) - .join(''); - this.url.searchParams.set('select', cleanedColumns); - if (count) { - this.headers['Prefer'] = `count=${count}`; - } - return new PostgrestFilterBuilder_1$2.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - fetch: this.fetch, - allowEmpty: false, - }); - } - /** - * Perform an INSERT into the table or view. - * - * By default, inserted rows are not returned. To return it, chain the call - * with `.select()`. - * - * @param values - The values to insert. Pass an object to insert a single row - * or an array to insert multiple rows. - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count inserted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - * - * @param options.defaultToNull - Make missing fields default to `null`. - * Otherwise, use the default value for the column. Only applies for bulk - * inserts. - */ - insert(values, { count, defaultToNull = true, } = {}) { - const method = 'POST'; - const prefersHeaders = []; - if (this.headers['Prefer']) { - prefersHeaders.push(this.headers['Prefer']); - } - if (count) { - prefersHeaders.push(`count=${count}`); - } - if (!defaultToNull) { - prefersHeaders.push('missing=default'); - } - this.headers['Prefer'] = prefersHeaders.join(','); - if (Array.isArray(values)) { - const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); - if (columns.length > 0) { - const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); - this.url.searchParams.set('columns', uniqueColumns.join(',')); - } - } - return new PostgrestFilterBuilder_1$2.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: this.fetch, - allowEmpty: false, - }); - } - /** - * Perform an UPSERT on the table or view. Depending on the column(s) passed - * to `onConflict`, `.upsert()` allows you to perform the equivalent of - * `.insert()` if a row with the corresponding `onConflict` columns doesn't - * exist, or if it does exist, perform an alternative action depending on - * `ignoreDuplicates`. - * - * By default, upserted rows are not returned. To return it, chain the call - * with `.select()`. - * - * @param values - The values to upsert with. Pass an object to upsert a - * single row or an array to upsert multiple rows. - * - * @param options - Named parameters - * - * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how - * duplicate rows are determined. Two rows are duplicates if all the - * `onConflict` columns are equal. - * - * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If - * `false`, duplicate rows are merged with existing rows. - * - * @param options.count - Count algorithm to use to count upserted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - * - * @param options.defaultToNull - Make missing fields default to `null`. - * Otherwise, use the default value for the column. This only applies when - * inserting new rows, not when merging with existing rows under - * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. - */ - upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { - const method = 'POST'; - const prefersHeaders = [`resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`]; - if (onConflict !== undefined) - this.url.searchParams.set('on_conflict', onConflict); - if (this.headers['Prefer']) { - prefersHeaders.push(this.headers['Prefer']); - } - if (count) { - prefersHeaders.push(`count=${count}`); - } - if (!defaultToNull) { - prefersHeaders.push('missing=default'); - } - this.headers['Prefer'] = prefersHeaders.join(','); - if (Array.isArray(values)) { - const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); - if (columns.length > 0) { - const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); - this.url.searchParams.set('columns', uniqueColumns.join(',')); - } - } - return new PostgrestFilterBuilder_1$2.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: this.fetch, - allowEmpty: false, - }); - } - /** - * Perform an UPDATE on the table or view. - * - * By default, updated rows are not returned. To return it, chain the call - * with `.select()` after filters. - * - * @param values - The values to update with - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count updated rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - update(values, { count, } = {}) { - const method = 'PATCH'; - const prefersHeaders = []; - if (this.headers['Prefer']) { - prefersHeaders.push(this.headers['Prefer']); - } - if (count) { - prefersHeaders.push(`count=${count}`); - } - this.headers['Prefer'] = prefersHeaders.join(','); - return new PostgrestFilterBuilder_1$2.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: this.fetch, - allowEmpty: false, - }); - } - /** - * Perform a DELETE on the table or view. - * - * By default, deleted rows are not returned. To return it, chain the call - * with `.select()` after filters. - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count deleted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - delete({ count, } = {}) { - const method = 'DELETE'; - const prefersHeaders = []; - if (count) { - prefersHeaders.push(`count=${count}`); - } - if (this.headers['Prefer']) { - prefersHeaders.unshift(this.headers['Prefer']); - } - this.headers['Prefer'] = prefersHeaders.join(','); - return new PostgrestFilterBuilder_1$2.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - fetch: this.fetch, - allowEmpty: false, - }); - } - } - PostgrestQueryBuilder$1.default = PostgrestQueryBuilder; - - var constants = {}; - - var version$4 = {}; - - Object.defineProperty(version$4, "__esModule", { value: true }); - version$4.version = void 0; - version$4.version = '0.0.0-automated'; - - Object.defineProperty(constants, "__esModule", { value: true }); - constants.DEFAULT_HEADERS = void 0; - const version_1 = version$4; - constants.DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version_1.version}` }; - - var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(PostgrestClient$2, "__esModule", { value: true }); - const PostgrestQueryBuilder_1$1 = __importDefault$1(PostgrestQueryBuilder$1); - const PostgrestFilterBuilder_1$1 = __importDefault$1(PostgrestFilterBuilder$1); - const constants_1 = constants; - /** - * PostgREST client. - * - * @typeParam Database - Types for the schema from the [type - * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) - * - * @typeParam SchemaName - Postgres schema to switch to. Must be a string - * literal, the same one passed to the constructor. If the schema is not - * `"public"`, this must be supplied manually. - */ - let PostgrestClient$1 = class PostgrestClient { - // TODO: Add back shouldThrowOnError once we figure out the typings - /** - * Creates a PostgREST client. - * - * @param url - URL of the PostgREST endpoint - * @param options - Named parameters - * @param options.headers - Custom headers - * @param options.schema - Postgres schema to switch to - * @param options.fetch - Custom fetch - */ - constructor(url, { headers = {}, schema, fetch, } = {}) { - this.url = url; - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.schemaName = schema; - this.fetch = fetch; - } - /** - * Perform a query on a table or a view. - * - * @param relation - The table or view name to query - */ - from(relation) { - const url = new URL(`${this.url}/${relation}`); - return new PostgrestQueryBuilder_1$1.default(url, { - headers: Object.assign({}, this.headers), - schema: this.schemaName, - fetch: this.fetch, - }); - } - /** - * Select a schema to query or perform an function (rpc) call. - * - * The schema needs to be on the list of exposed schemas inside Supabase. - * - * @param schema - The schema to query - */ - schema(schema) { - return new PostgrestClient(this.url, { - headers: this.headers, - schema, - fetch: this.fetch, - }); - } - /** - * Perform a function call. - * - * @param fn - The function name to call - * @param args - The arguments to pass to the function call - * @param options - Named parameters - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * @param options.get - When set to `true`, the function will be called with - * read-only access mode. - * @param options.count - Count algorithm to use to count rows returned by the - * function. Only applicable for [set-returning - * functions](https://www.postgresql.org/docs/current/functions-srf.html). - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - rpc(fn, args = {}, { head = false, get = false, count, } = {}) { - let method; - const url = new URL(`${this.url}/rpc/${fn}`); - let body; - if (head || get) { - method = head ? 'HEAD' : 'GET'; - Object.entries(args) - // params with undefined value needs to be filtered out, otherwise it'll - // show up as `?param=undefined` - .filter(([_, value]) => value !== undefined) - // array values need special syntax - .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) - .forEach(([name, value]) => { - url.searchParams.append(name, value); - }); - } - else { - method = 'POST'; - body = args; - } - const headers = Object.assign({}, this.headers); - if (count) { - headers['Prefer'] = `count=${count}`; - } - return new PostgrestFilterBuilder_1$1.default({ - method, - url, - headers, - schema: this.schemaName, - body, - fetch: this.fetch, - allowEmpty: false, - }); - } - }; - PostgrestClient$2.default = PostgrestClient$1; - - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(cjs, "__esModule", { value: true }); - cjs.PostgrestBuilder = cjs.PostgrestTransformBuilder = cjs.PostgrestFilterBuilder = cjs.PostgrestQueryBuilder = PostgrestClient = cjs.PostgrestClient = void 0; - // Always update wrapper.mjs when updating this file. - const PostgrestClient_1 = __importDefault(PostgrestClient$2); - var PostgrestClient = cjs.PostgrestClient = PostgrestClient_1.default; - const PostgrestQueryBuilder_1 = __importDefault(PostgrestQueryBuilder$1); - cjs.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; - const PostgrestFilterBuilder_1 = __importDefault(PostgrestFilterBuilder$1); - cjs.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; - const PostgrestTransformBuilder_1 = __importDefault(PostgrestTransformBuilder$1); - cjs.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; - const PostgrestBuilder_1 = __importDefault(PostgrestBuilder$1); - cjs.PostgrestBuilder = PostgrestBuilder_1.default; - cjs.default = { - PostgrestClient: PostgrestClient_1.default, - PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, - PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, - PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, - PostgrestBuilder: PostgrestBuilder_1.default, - }; - - const version$3 = '2.10.2'; - - const DEFAULT_HEADERS$3 = { 'X-Client-Info': `realtime-js/${version$3}` }; - const VSN = '1.0.0'; - const DEFAULT_TIMEOUT = 10000; - const WS_CLOSE_NORMAL = 1000; - var SOCKET_STATES; - (function (SOCKET_STATES) { - SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; - SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; - SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; - SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; - })(SOCKET_STATES || (SOCKET_STATES = {})); - var CHANNEL_STATES; - (function (CHANNEL_STATES) { - CHANNEL_STATES["closed"] = "closed"; - CHANNEL_STATES["errored"] = "errored"; - CHANNEL_STATES["joined"] = "joined"; - CHANNEL_STATES["joining"] = "joining"; - CHANNEL_STATES["leaving"] = "leaving"; - })(CHANNEL_STATES || (CHANNEL_STATES = {})); - var CHANNEL_EVENTS; - (function (CHANNEL_EVENTS) { - CHANNEL_EVENTS["close"] = "phx_close"; - CHANNEL_EVENTS["error"] = "phx_error"; - CHANNEL_EVENTS["join"] = "phx_join"; - CHANNEL_EVENTS["reply"] = "phx_reply"; - CHANNEL_EVENTS["leave"] = "phx_leave"; - CHANNEL_EVENTS["access_token"] = "access_token"; - })(CHANNEL_EVENTS || (CHANNEL_EVENTS = {})); - var TRANSPORTS; - (function (TRANSPORTS) { - TRANSPORTS["websocket"] = "websocket"; - })(TRANSPORTS || (TRANSPORTS = {})); - var CONNECTION_STATE; - (function (CONNECTION_STATE) { - CONNECTION_STATE["Connecting"] = "connecting"; - CONNECTION_STATE["Open"] = "open"; - CONNECTION_STATE["Closing"] = "closing"; - CONNECTION_STATE["Closed"] = "closed"; - })(CONNECTION_STATE || (CONNECTION_STATE = {})); - - // This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe - // License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md - class Serializer { - constructor() { - this.HEADER_LENGTH = 1; - } - decode(rawPayload, callback) { - if (rawPayload.constructor === ArrayBuffer) { - return callback(this._binaryDecode(rawPayload)); - } - if (typeof rawPayload === 'string') { - return callback(JSON.parse(rawPayload)); - } - return callback({}); - } - _binaryDecode(buffer) { - const view = new DataView(buffer); - const decoder = new TextDecoder(); - return this._decodeBroadcast(buffer, view, decoder); - } - _decodeBroadcast(buffer, view, decoder) { - const topicSize = view.getUint8(1); - const eventSize = view.getUint8(2); - let offset = this.HEADER_LENGTH + 2; - const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); - offset = offset + topicSize; - const event = decoder.decode(buffer.slice(offset, offset + eventSize)); - offset = offset + eventSize; - const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); - return { ref: null, topic: topic, event: event, payload: data }; - } - } - - /** - * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. - * - * @example - * let reconnectTimer = new Timer(() => this.connect(), function(tries){ - * return [1000, 5000, 10000][tries - 1] || 10000 - * }) - * reconnectTimer.scheduleTimeout() // fires after 1000 - * reconnectTimer.scheduleTimeout() // fires after 5000 - * reconnectTimer.reset() - * reconnectTimer.scheduleTimeout() // fires after 1000 - */ - class Timer { - constructor(callback, timerCalc) { - this.callback = callback; - this.timerCalc = timerCalc; - this.timer = undefined; - this.tries = 0; - this.callback = callback; - this.timerCalc = timerCalc; - } - reset() { - this.tries = 0; - clearTimeout(this.timer); - } - // Cancels any previous scheduleTimeout and schedules callback - scheduleTimeout() { - clearTimeout(this.timer); - this.timer = setTimeout(() => { - this.tries = this.tries + 1; - this.callback(); - }, this.timerCalc(this.tries + 1)); - } - } - - /** - * Helpers to convert the change Payload into native JS types. - */ - // Adapted from epgsql (src/epgsql_binary.erl), this module licensed under - // 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE - var PostgresTypes; - (function (PostgresTypes) { - PostgresTypes["abstime"] = "abstime"; - PostgresTypes["bool"] = "bool"; - PostgresTypes["date"] = "date"; - PostgresTypes["daterange"] = "daterange"; - PostgresTypes["float4"] = "float4"; - PostgresTypes["float8"] = "float8"; - PostgresTypes["int2"] = "int2"; - PostgresTypes["int4"] = "int4"; - PostgresTypes["int4range"] = "int4range"; - PostgresTypes["int8"] = "int8"; - PostgresTypes["int8range"] = "int8range"; - PostgresTypes["json"] = "json"; - PostgresTypes["jsonb"] = "jsonb"; - PostgresTypes["money"] = "money"; - PostgresTypes["numeric"] = "numeric"; - PostgresTypes["oid"] = "oid"; - PostgresTypes["reltime"] = "reltime"; - PostgresTypes["text"] = "text"; - PostgresTypes["time"] = "time"; - PostgresTypes["timestamp"] = "timestamp"; - PostgresTypes["timestamptz"] = "timestamptz"; - PostgresTypes["timetz"] = "timetz"; - PostgresTypes["tsrange"] = "tsrange"; - PostgresTypes["tstzrange"] = "tstzrange"; - })(PostgresTypes || (PostgresTypes = {})); - /** - * Takes an array of columns and an object of string values then converts each string value - * to its mapped type. - * - * @param {{name: String, type: String}[]} columns - * @param {Object} record - * @param {Object} options The map of various options that can be applied to the mapper - * @param {Array} options.skipTypes The array of types that should not be converted - * - * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) - * //=>{ first_name: 'Paul', age: 33 } - */ - const convertChangeData = (columns, record, options = {}) => { - var _a; - const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; - return Object.keys(record).reduce((acc, rec_key) => { - acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes); - return acc; - }, {}); - }; - /** - * Converts the value of an individual column. - * - * @param {String} columnName The column that you want to convert - * @param {{name: String, type: String}[]} columns All of the columns - * @param {Object} record The map of string values - * @param {Array} skipTypes An array of types that should not be converted - * @return {object} Useless information - * - * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) - * //=> 33 - * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) - * //=> "33" - */ - const convertColumn = (columnName, columns, record, skipTypes) => { - const column = columns.find((x) => x.name === columnName); - const colType = column === null || column === void 0 ? void 0 : column.type; - const value = record[columnName]; - if (colType && !skipTypes.includes(colType)) { - return convertCell(colType, value); - } - return noop$1(value); - }; - /** - * If the value of the cell is `null`, returns null. - * Otherwise converts the string value to the correct type. - * @param {String} type A postgres column type - * @param {String} value The cell value - * - * @example convertCell('bool', 't') - * //=> true - * @example convertCell('int8', '10') - * //=> 10 - * @example convertCell('_int4', '{1,2,3,4}') - * //=> [1,2,3,4] - */ - const convertCell = (type, value) => { - // if data type is an array - if (type.charAt(0) === '_') { - const dataType = type.slice(1, type.length); - return toArray(value, dataType); - } - // If not null, convert to correct type. - switch (type) { - case PostgresTypes.bool: - return toBoolean(value); - case PostgresTypes.float4: - case PostgresTypes.float8: - case PostgresTypes.int2: - case PostgresTypes.int4: - case PostgresTypes.int8: - case PostgresTypes.numeric: - case PostgresTypes.oid: - return toNumber(value); - case PostgresTypes.json: - case PostgresTypes.jsonb: - return toJson(value); - case PostgresTypes.timestamp: - return toTimestampString(value); // Format to be consistent with PostgREST - case PostgresTypes.abstime: // To allow users to cast it based on Timezone - case PostgresTypes.date: // To allow users to cast it based on Timezone - case PostgresTypes.daterange: - case PostgresTypes.int4range: - case PostgresTypes.int8range: - case PostgresTypes.money: - case PostgresTypes.reltime: // To allow users to cast it based on Timezone - case PostgresTypes.text: - case PostgresTypes.time: // To allow users to cast it based on Timezone - case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone - case PostgresTypes.timetz: // To allow users to cast it based on Timezone - case PostgresTypes.tsrange: - case PostgresTypes.tstzrange: - return noop$1(value); - default: - // Return the value for remaining types - return noop$1(value); - } - }; - const noop$1 = (value) => { - return value; - }; - const toBoolean = (value) => { - switch (value) { - case 't': - return true; - case 'f': - return false; - default: - return value; - } - }; - const toNumber = (value) => { - if (typeof value === 'string') { - const parsedValue = parseFloat(value); - if (!Number.isNaN(parsedValue)) { - return parsedValue; - } - } - return value; - }; - const toJson = (value) => { - if (typeof value === 'string') { - try { - return JSON.parse(value); - } - catch (error) { - console.log(`JSON parse error: ${error}`); - return value; - } - } - return value; - }; - /** - * Converts a Postgres Array into a native JS array - * - * @example toArray('{}', 'int4') - * //=> [] - * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') - * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] - * @example toArray([1,2,3,4], 'int4') - * //=> [1,2,3,4] - */ - const toArray = (value, type) => { - if (typeof value !== 'string') { - return value; - } - const lastIdx = value.length - 1; - const closeBrace = value[lastIdx]; - const openBrace = value[0]; - // Confirm value is a Postgres array by checking curly brackets - if (openBrace === '{' && closeBrace === '}') { - let arr; - const valTrim = value.slice(1, lastIdx); - // TODO: find a better solution to separate Postgres array data - try { - arr = JSON.parse('[' + valTrim + ']'); - } - catch (_) { - // WARNING: splitting on comma does not cover all edge cases - arr = valTrim ? valTrim.split(',') : []; - } - return arr.map((val) => convertCell(type, val)); - } - return value; - }; - /** - * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' - * See https://github.com/supabase/supabase/issues/18 - * - * @example toTimestampString('2019-09-10 00:00:00') - * //=> '2019-09-10T00:00:00' - */ - const toTimestampString = (value) => { - if (typeof value === 'string') { - return value.replace(' ', 'T'); - } - return value; - }; - const httpEndpointURL = (socketUrl) => { - let url = socketUrl; - url = url.replace(/^ws/i, 'http'); - url = url.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i, ''); - return url.replace(/\/+$/, ''); - }; - - class Push { - /** - * Initializes the Push - * - * @param channel The Channel - * @param event The event, for example `"phx_join"` - * @param payload The payload, for example `{user_id: 123}` - * @param timeout The push timeout in milliseconds - */ - constructor(channel, event, payload = {}, timeout = DEFAULT_TIMEOUT) { - this.channel = channel; - this.event = event; - this.payload = payload; - this.timeout = timeout; - this.sent = false; - this.timeoutTimer = undefined; - this.ref = ''; - this.receivedResp = null; - this.recHooks = []; - this.refEvent = null; - } - resend(timeout) { - this.timeout = timeout; - this._cancelRefEvent(); - this.ref = ''; - this.refEvent = null; - this.receivedResp = null; - this.sent = false; - this.send(); - } - send() { - if (this._hasReceived('timeout')) { - return; - } - this.startTimeout(); - this.sent = true; - this.channel.socket.push({ - topic: this.channel.topic, - event: this.event, - payload: this.payload, - ref: this.ref, - join_ref: this.channel._joinRef(), - }); - } - updatePayload(payload) { - this.payload = Object.assign(Object.assign({}, this.payload), payload); - } - receive(status, callback) { - var _a; - if (this._hasReceived(status)) { - callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); - } - this.recHooks.push({ status, callback }); - return this; - } - startTimeout() { - if (this.timeoutTimer) { - return; - } - this.ref = this.channel.socket._makeRef(); - this.refEvent = this.channel._replyEventName(this.ref); - const callback = (payload) => { - this._cancelRefEvent(); - this._cancelTimeout(); - this.receivedResp = payload; - this._matchReceive(payload); - }; - this.channel._on(this.refEvent, {}, callback); - this.timeoutTimer = setTimeout(() => { - this.trigger('timeout', {}); - }, this.timeout); - } - trigger(status, response) { - if (this.refEvent) - this.channel._trigger(this.refEvent, { status, response }); - } - destroy() { - this._cancelRefEvent(); - this._cancelTimeout(); - } - _cancelRefEvent() { - if (!this.refEvent) { - return; - } - this.channel._off(this.refEvent, {}); - } - _cancelTimeout() { - clearTimeout(this.timeoutTimer); - this.timeoutTimer = undefined; - } - _matchReceive({ status, response, }) { - this.recHooks - .filter((h) => h.status === status) - .forEach((h) => h.callback(response)); - } - _hasReceived(status) { - return this.receivedResp && this.receivedResp.status === status; - } - } - - /* - This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js - License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md - */ - exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; - (function (REALTIME_PRESENCE_LISTEN_EVENTS) { - REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; - REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; - REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; - })(exports.REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = {})); - class RealtimePresence { - /** - * Initializes the Presence. - * - * @param channel - The RealtimeChannel - * @param opts - The options, - * for example `{events: {state: 'state', diff: 'diff'}}` - */ - constructor(channel, opts) { - this.channel = channel; - this.state = {}; - this.pendingDiffs = []; - this.joinRef = null; - this.caller = { - onJoin: () => { }, - onLeave: () => { }, - onSync: () => { }, - }; - const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { - state: 'presence_state', - diff: 'presence_diff', - }; - this.channel._on(events.state, {}, (newState) => { - const { onJoin, onLeave, onSync } = this.caller; - this.joinRef = this.channel._joinRef(); - this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); - this.pendingDiffs.forEach((diff) => { - this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); - }); - this.pendingDiffs = []; - onSync(); - }); - this.channel._on(events.diff, {}, (diff) => { - const { onJoin, onLeave, onSync } = this.caller; - if (this.inPendingSyncState()) { - this.pendingDiffs.push(diff); - } - else { - this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); - onSync(); - } - }); - this.onJoin((key, currentPresences, newPresences) => { - this.channel._trigger('presence', { - event: 'join', - key, - currentPresences, - newPresences, - }); - }); - this.onLeave((key, currentPresences, leftPresences) => { - this.channel._trigger('presence', { - event: 'leave', - key, - currentPresences, - leftPresences, - }); - }); - this.onSync(() => { - this.channel._trigger('presence', { event: 'sync' }); - }); - } - /** - * Used to sync the list of presences on the server with the - * client's state. - * - * An optional `onJoin` and `onLeave` callback can be provided to - * react to changes in the client's local presences across - * disconnects and reconnects with the server. - * - * @internal - */ - static syncState(currentState, newState, onJoin, onLeave) { - const state = this.cloneDeep(currentState); - const transformedState = this.transformState(newState); - const joins = {}; - const leaves = {}; - this.map(state, (key, presences) => { - if (!transformedState[key]) { - leaves[key] = presences; - } - }); - this.map(transformedState, (key, newPresences) => { - const currentPresences = state[key]; - if (currentPresences) { - const newPresenceRefs = newPresences.map((m) => m.presence_ref); - const curPresenceRefs = currentPresences.map((m) => m.presence_ref); - const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); - const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); - if (joinedPresences.length > 0) { - joins[key] = joinedPresences; - } - if (leftPresences.length > 0) { - leaves[key] = leftPresences; - } - } - else { - joins[key] = newPresences; - } - }); - return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); - } - /** - * Used to sync a diff of presence join and leave events from the - * server, as they happen. - * - * Like `syncState`, `syncDiff` accepts optional `onJoin` and - * `onLeave` callbacks to react to a user joining or leaving from a - * device. - * - * @internal - */ - static syncDiff(state, diff, onJoin, onLeave) { - const { joins, leaves } = { - joins: this.transformState(diff.joins), - leaves: this.transformState(diff.leaves), - }; - if (!onJoin) { - onJoin = () => { }; - } - if (!onLeave) { - onLeave = () => { }; - } - this.map(joins, (key, newPresences) => { - var _a; - const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; - state[key] = this.cloneDeep(newPresences); - if (currentPresences.length > 0) { - const joinedPresenceRefs = state[key].map((m) => m.presence_ref); - const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); - state[key].unshift(...curPresences); - } - onJoin(key, currentPresences, newPresences); - }); - this.map(leaves, (key, leftPresences) => { - let currentPresences = state[key]; - if (!currentPresences) - return; - const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); - currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); - state[key] = currentPresences; - onLeave(key, currentPresences, leftPresences); - if (currentPresences.length === 0) - delete state[key]; - }); - return state; - } - /** @internal */ - static map(obj, func) { - return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); - } - /** - * Remove 'metas' key - * Change 'phx_ref' to 'presence_ref' - * Remove 'phx_ref' and 'phx_ref_prev' - * - * @example - * // returns { - * abc123: [ - * { presence_ref: '2', user_id: 1 }, - * { presence_ref: '3', user_id: 2 } - * ] - * } - * RealtimePresence.transformState({ - * abc123: { - * metas: [ - * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, - * { phx_ref: '3', user_id: 2 } - * ] - * } - * }) - * - * @internal - */ - static transformState(state) { - state = this.cloneDeep(state); - return Object.getOwnPropertyNames(state).reduce((newState, key) => { - const presences = state[key]; - if ('metas' in presences) { - newState[key] = presences.metas.map((presence) => { - presence['presence_ref'] = presence['phx_ref']; - delete presence['phx_ref']; - delete presence['phx_ref_prev']; - return presence; - }); - } - else { - newState[key] = presences; - } - return newState; - }, {}); - } - /** @internal */ - static cloneDeep(obj) { - return JSON.parse(JSON.stringify(obj)); - } - /** @internal */ - onJoin(callback) { - this.caller.onJoin = callback; - } - /** @internal */ - onLeave(callback) { - this.caller.onLeave = callback; - } - /** @internal */ - onSync(callback) { - this.caller.onSync = callback; - } - /** @internal */ - inPendingSyncState() { - return !this.joinRef || this.joinRef !== this.channel._joinRef(); - } - } - - exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; - (function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; - })(exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); - exports.REALTIME_LISTEN_TYPES = void 0; - (function (REALTIME_LISTEN_TYPES) { - REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; - REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; - /** - * listen to Postgres changes. - */ - REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; - })(exports.REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = {})); - exports.REALTIME_SUBSCRIBE_STATES = void 0; - (function (REALTIME_SUBSCRIBE_STATES) { - REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; - REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; - REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; - REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; - })(exports.REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = {})); - const REALTIME_CHANNEL_STATES = CHANNEL_STATES; - /** A channel is the basic building block of Realtime - * and narrows the scope of data flow to subscribed clients. - * You can think of a channel as a chatroom where participants are able to see who's online - * and send and receive messages. - */ - class RealtimeChannel { - constructor( - /** Topic name can be any string. */ - topic, params = { config: {} }, socket) { - this.topic = topic; - this.params = params; - this.socket = socket; - this.bindings = {}; - this.state = CHANNEL_STATES.closed; - this.joinedOnce = false; - this.pushBuffer = []; - this.subTopic = topic.replace(/^realtime:/i, ''); - this.params.config = Object.assign({ - broadcast: { ack: false, self: false }, - presence: { key: '' }, - private: false, - }, params.config); - this.timeout = this.socket.timeout; - this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout); - this.rejoinTimer = new Timer(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); - this.joinPush.receive('ok', () => { - this.state = CHANNEL_STATES.joined; - this.rejoinTimer.reset(); - this.pushBuffer.forEach((pushEvent) => pushEvent.send()); - this.pushBuffer = []; - }); - this._onClose(() => { - this.rejoinTimer.reset(); - this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); - this.state = CHANNEL_STATES.closed; - this.socket._remove(this); - }); - this._onError((reason) => { - if (this._isLeaving() || this._isClosed()) { - return; - } - this.socket.log('channel', `error ${this.topic}`, reason); - this.state = CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this.joinPush.receive('timeout', () => { - if (!this._isJoining()) { - return; - } - this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); - this.state = CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this._on(CHANNEL_EVENTS.reply, {}, (payload, ref) => { - this._trigger(this._replyEventName(ref), payload); - }); - this.presence = new RealtimePresence(this); - this.broadcastEndpointURL = - httpEndpointURL(this.socket.endPoint) + '/api/broadcast'; - } - /** Subscribe registers your client with the server */ - subscribe(callback, timeout = this.timeout) { - var _a, _b; - if (!this.socket.isConnected()) { - this.socket.connect(); - } - if (this.joinedOnce) { - throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance`; - } - else { - const { config: { broadcast, presence, private: isPrivate }, } = this.params; - this._onError((e) => callback && callback('CHANNEL_ERROR', e)); - this._onClose(() => callback && callback('CLOSED')); - const accessTokenPayload = {}; - const config = { - broadcast, - presence, - postgres_changes: (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : [], - private: isPrivate, - }; - if (this.socket.accessToken) { - accessTokenPayload.access_token = this.socket.accessToken; - } - this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); - this.joinedOnce = true; - this._rejoin(timeout); - this.joinPush - .receive('ok', ({ postgres_changes: serverPostgresFilters, }) => { - var _a; - this.socket.accessToken && - this.socket.setAuth(this.socket.accessToken); - if (serverPostgresFilters === undefined) { - callback && callback('SUBSCRIBED'); - return; - } - else { - const clientPostgresBindings = this.bindings.postgres_changes; - const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; - const newPostgresBindings = []; - for (let i = 0; i < bindingsLen; i++) { - const clientPostgresBinding = clientPostgresBindings[i]; - const { filter: { event, schema, table, filter }, } = clientPostgresBinding; - const serverPostgresFilter = serverPostgresFilters && serverPostgresFilters[i]; - if (serverPostgresFilter && - serverPostgresFilter.event === event && - serverPostgresFilter.schema === schema && - serverPostgresFilter.table === table && - serverPostgresFilter.filter === filter) { - newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); - } - else { - this.unsubscribe(); - callback && - callback('CHANNEL_ERROR', new Error('mismatch between server and client bindings for postgres changes')); - return; - } - } - this.bindings.postgres_changes = newPostgresBindings; - callback && callback('SUBSCRIBED'); - return; - } - }) - .receive('error', (error) => { - callback && - callback('CHANNEL_ERROR', new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); - return; - }) - .receive('timeout', () => { - callback && callback('TIMED_OUT'); - return; - }); - } - return this; - } - presenceState() { - return this.presence.state; - } - async track(payload, opts = {}) { - return await this.send({ - type: 'presence', - event: 'track', - payload, - }, opts.timeout || this.timeout); - } - async untrack(opts = {}) { - return await this.send({ - type: 'presence', - event: 'untrack', - }, opts); - } - on(type, filter, callback) { - return this._on(type, filter, callback); - } - /** - * Sends a message into the channel. - * - * @param args Arguments to send to channel - * @param args.type The type of event to send - * @param args.event The name of the event being sent - * @param args.payload Payload to be sent - * @param opts Options to be used during the send process - */ - async send(args, opts = {}) { - var _a, _b; - if (!this._canPush() && args.type === 'broadcast') { - const { event, payload: endpoint_payload } = args; - const options = { - method: 'POST', - headers: { - Authorization: this.socket.accessToken - ? `Bearer ${this.socket.accessToken}` - : '', - apikey: this.socket.apiKey ? this.socket.apiKey : '', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - messages: [ - { topic: this.subTopic, event, payload: endpoint_payload }, - ], - }), - }; - try { - const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); - await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); - return response.ok ? 'ok' : 'error'; - } - catch (error) { - if (error.name === 'AbortError') { - return 'timed out'; - } - else { - return 'error'; - } - } - } - else { - return new Promise((resolve) => { - var _a, _b, _c; - const push = this._push(args.type, args, opts.timeout || this.timeout); - if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { - resolve('ok'); - } - push.receive('ok', () => resolve('ok')); - push.receive('error', () => resolve('error')); - push.receive('timeout', () => resolve('timed out')); - }); - } - } - updateJoinPayload(payload) { - this.joinPush.updatePayload(payload); - } - /** - * Leaves the channel. - * - * Unsubscribes from server events, and instructs channel to terminate on server. - * Triggers onClose() hooks. - * - * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: - * channel.unsubscribe().receive("ok", () => alert("left!") ) - */ - unsubscribe(timeout = this.timeout) { - this.state = CHANNEL_STATES.leaving; - const onClose = () => { - this.socket.log('channel', `leave ${this.topic}`); - this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef()); - }; - this.rejoinTimer.reset(); - // Destroy joinPush to avoid connection timeouts during unscription phase - this.joinPush.destroy(); - return new Promise((resolve) => { - const leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout); - leavePush - .receive('ok', () => { - onClose(); - resolve('ok'); - }) - .receive('timeout', () => { - onClose(); - resolve('timed out'); - }) - .receive('error', () => { - resolve('error'); - }); - leavePush.send(); - if (!this._canPush()) { - leavePush.trigger('ok', {}); - } - }); - } - /** @internal */ - async _fetchWithTimeout(url, options, timeout) { - const controller = new AbortController(); - const id = setTimeout(() => controller.abort(), timeout); - const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); - clearTimeout(id); - return response; - } - /** @internal */ - _push(event, payload, timeout = this.timeout) { - if (!this.joinedOnce) { - throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; - } - let pushEvent = new Push(this, event, payload, timeout); - if (this._canPush()) { - pushEvent.send(); - } - else { - pushEvent.startTimeout(); - this.pushBuffer.push(pushEvent); - } - return pushEvent; - } - /** - * Overridable message hook - * - * Receives all events for specialized message handling before dispatching to the channel callbacks. - * Must return the payload, modified or unmodified. - * - * @internal - */ - _onMessage(_event, payload, _ref) { - return payload; - } - /** @internal */ - _isMember(topic) { - return this.topic === topic; - } - /** @internal */ - _joinRef() { - return this.joinPush.ref; - } - /** @internal */ - _trigger(type, payload, ref) { - var _a, _b; - const typeLower = type.toLocaleLowerCase(); - const { close, error, leave, join } = CHANNEL_EVENTS; - const events = [close, error, leave, join]; - if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { - return; - } - let handledPayload = this._onMessage(typeLower, payload, ref); - if (payload && !handledPayload) { - throw 'channel onMessage callbacks must return the payload, modified or unmodified'; - } - if (['insert', 'update', 'delete'].includes(typeLower)) { - (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { - var _a, _b, _c; - return (((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || - ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower); - }).map((bind) => bind.callback(handledPayload, ref)); - } - else { - (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { - var _a, _b, _c, _d, _e, _f; - if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { - if ('id' in bind) { - const bindId = bind.id; - const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; - return (bindId && - ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && - (bindEvent === '*' || - (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === - ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); - } - else { - const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); - return (bindEvent === '*' || - bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase())); - } - } - else { - return bind.type.toLocaleLowerCase() === typeLower; - } - }).map((bind) => { - if (typeof handledPayload === 'object' && 'ids' in handledPayload) { - const postgresChanges = handledPayload.data; - const { schema, table, commit_timestamp, type, errors } = postgresChanges; - const enrichedPayload = { - schema: schema, - table: table, - commit_timestamp: commit_timestamp, - eventType: type, - new: {}, - old: {}, - errors: errors, - }; - handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); - } - bind.callback(handledPayload, ref); - }); - } - } - /** @internal */ - _isClosed() { - return this.state === CHANNEL_STATES.closed; - } - /** @internal */ - _isJoined() { - return this.state === CHANNEL_STATES.joined; - } - /** @internal */ - _isJoining() { - return this.state === CHANNEL_STATES.joining; - } - /** @internal */ - _isLeaving() { - return this.state === CHANNEL_STATES.leaving; - } - /** @internal */ - _replyEventName(ref) { - return `chan_reply_${ref}`; - } - /** @internal */ - _on(type, filter, callback) { - const typeLower = type.toLocaleLowerCase(); - const binding = { - type: typeLower, - filter: filter, - callback: callback, - }; - if (this.bindings[typeLower]) { - this.bindings[typeLower].push(binding); - } - else { - this.bindings[typeLower] = [binding]; - } - return this; - } - /** @internal */ - _off(type, filter) { - const typeLower = type.toLocaleLowerCase(); - this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { - var _a; - return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && - RealtimeChannel.isEqual(bind.filter, filter)); - }); - return this; - } - /** @internal */ - static isEqual(obj1, obj2) { - if (Object.keys(obj1).length !== Object.keys(obj2).length) { - return false; - } - for (const k in obj1) { - if (obj1[k] !== obj2[k]) { - return false; - } - } - return true; - } - /** @internal */ - _rejoinUntilConnected() { - this.rejoinTimer.scheduleTimeout(); - if (this.socket.isConnected()) { - this._rejoin(); - } - } - /** - * Registers a callback that will be executed when the channel closes. - * - * @internal - */ - _onClose(callback) { - this._on(CHANNEL_EVENTS.close, {}, callback); - } - /** - * Registers a callback that will be executed when the channel encounteres an error. - * - * @internal - */ - _onError(callback) { - this._on(CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); - } - /** - * Returns `true` if the socket is connected and the channel has been joined. - * - * @internal - */ - _canPush() { - return this.socket.isConnected() && this._isJoined(); - } - /** @internal */ - _rejoin(timeout = this.timeout) { - if (this._isLeaving()) { - return; - } - this.socket._leaveOpenTopic(this.topic); - this.state = CHANNEL_STATES.joining; - this.joinPush.resend(timeout); - } - /** @internal */ - _getPayloadRecords(payload) { - const records = { - new: {}, - old: {}, - }; - if (payload.type === 'INSERT' || payload.type === 'UPDATE') { - records.new = convertChangeData(payload.columns, payload.record); - } - if (payload.type === 'UPDATE' || payload.type === 'DELETE') { - records.old = convertChangeData(payload.columns, payload.old_record); - } - return records; - } - } - - const noop = () => { }; - const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined'; - class RealtimeClient { - /** - * Initializes the Socket. - * - * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) - * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) - * @param options.transport The Websocket Transport, for example WebSocket. - * @param options.timeout The default timeout in milliseconds to trigger push timeouts. - * @param options.params The optional params to pass when connecting. - * @param options.headers The optional headers to pass when connecting. - * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. - * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } - * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) - * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. - * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. - */ - constructor(endPoint, options) { - var _a; - this.accessToken = null; - this.apiKey = null; - this.channels = []; - this.endPoint = ''; - this.httpEndpoint = ''; - this.headers = DEFAULT_HEADERS$3; - this.params = {}; - this.timeout = DEFAULT_TIMEOUT; - this.heartbeatIntervalMs = 30000; - this.heartbeatTimer = undefined; - this.pendingHeartbeatRef = null; - this.ref = 0; - this.logger = noop; - this.conn = null; - this.sendBuffer = []; - this.serializer = new Serializer(); - this.stateChangeCallbacks = { - open: [], - close: [], - error: [], - message: [], - }; - /** - * Use either custom fetch, if provided, or default fetch to make HTTP requests - * - * @internal - */ - this._resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`; - this.httpEndpoint = httpEndpointURL(endPoint); - if (options === null || options === void 0 ? void 0 : options.transport) { - this.transport = options.transport; - } - else { - this.transport = null; - } - if (options === null || options === void 0 ? void 0 : options.params) - this.params = options.params; - if (options === null || options === void 0 ? void 0 : options.headers) - this.headers = Object.assign(Object.assign({}, this.headers), options.headers); - if (options === null || options === void 0 ? void 0 : options.timeout) - this.timeout = options.timeout; - if (options === null || options === void 0 ? void 0 : options.logger) - this.logger = options.logger; - if (options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) - this.heartbeatIntervalMs = options.heartbeatIntervalMs; - const accessToken = (_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey; - if (accessToken) { - this.accessToken = accessToken; - this.apiKey = accessToken; - } - this.reconnectAfterMs = (options === null || options === void 0 ? void 0 : options.reconnectAfterMs) - ? options.reconnectAfterMs - : (tries) => { - return [1000, 2000, 5000, 10000][tries - 1] || 10000; - }; - this.encode = (options === null || options === void 0 ? void 0 : options.encode) - ? options.encode - : (payload, callback) => { - return callback(JSON.stringify(payload)); - }; - this.decode = (options === null || options === void 0 ? void 0 : options.decode) - ? options.decode - : this.serializer.decode.bind(this.serializer); - this.reconnectTimer = new Timer(async () => { - this.disconnect(); - this.connect(); - }, this.reconnectAfterMs); - this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); - } - /** - * Connects the socket, unless already connected. - */ - connect() { - if (this.conn) { - return; - } - if (this.transport) { - this.conn = new this.transport(this._endPointURL(), undefined, { - headers: this.headers, - }); - return; - } - if (NATIVE_WEBSOCKET_AVAILABLE) { - this.conn = new WebSocket(this._endPointURL()); - this.setupConnection(); - return; - } - this.conn = new WSWebSocketDummy(this._endPointURL(), undefined, { - close: () => { - this.conn = null; - }, - }); - new Promise(function (resolve, reject) { require(['ui5/ecosystem/demo/app/resources/browser'], resolve, reject); }).then(function (n) { return n.browser; }).then(({ default: WS }) => { - this.conn = new WS(this._endPointURL(), undefined, { - headers: this.headers, - }); - this.setupConnection(); - }); - } - /** - * Disconnects the socket. - * - * @param code A numeric status code to send on disconnect. - * @param reason A custom reason for the disconnect. - */ - disconnect(code, reason) { - if (this.conn) { - this.conn.onclose = function () { }; // noop - if (code) { - this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); - } - else { - this.conn.close(); - } - this.conn = null; - // remove open handles - this.heartbeatTimer && clearInterval(this.heartbeatTimer); - this.reconnectTimer.reset(); - } - } - /** - * Returns all created channels - */ - getChannels() { - return this.channels; - } - /** - * Unsubscribes and removes a single channel - * @param channel A RealtimeChannel instance - */ - async removeChannel(channel) { - const status = await channel.unsubscribe(); - if (this.channels.length === 0) { - this.disconnect(); - } - return status; - } - /** - * Unsubscribes and removes all channels - */ - async removeAllChannels() { - const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); - this.disconnect(); - return values_1; - } - /** - * Logs the message. - * - * For customized logging, `this.logger` can be overridden. - */ - log(kind, msg, data) { - this.logger(kind, msg, data); - } - /** - * Returns the current state of the socket. - */ - connectionState() { - switch (this.conn && this.conn.readyState) { - case SOCKET_STATES.connecting: - return CONNECTION_STATE.Connecting; - case SOCKET_STATES.open: - return CONNECTION_STATE.Open; - case SOCKET_STATES.closing: - return CONNECTION_STATE.Closing; - default: - return CONNECTION_STATE.Closed; - } - } - /** - * Returns `true` is the connection is open. - */ - isConnected() { - return this.connectionState() === CONNECTION_STATE.Open; - } - channel(topic, params = { config: {} }) { - const chan = new RealtimeChannel(`realtime:${topic}`, params, this); - this.channels.push(chan); - return chan; - } - /** - * Push out a message if the socket is connected. - * - * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. - */ - push(data) { - const { topic, event, payload, ref } = data; - const callback = () => { - this.encode(data, (result) => { - var _a; - (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); - }); - }; - this.log('push', `${topic} ${event} (${ref})`, payload); - if (this.isConnected()) { - callback(); - } - else { - this.sendBuffer.push(callback); - } - } - /** - * Sets the JWT access token used for channel subscription authorization and Realtime RLS. - * - * @param token A JWT string. - */ - setAuth(token) { - this.accessToken = token; - this.channels.forEach((channel) => { - token && channel.updateJoinPayload({ access_token: token }); - if (channel.joinedOnce && channel._isJoined()) { - channel._push(CHANNEL_EVENTS.access_token, { access_token: token }); - } - }); - } - /** - * Return the next message ref, accounting for overflows - * - * @internal - */ - _makeRef() { - let newRef = this.ref + 1; - if (newRef === this.ref) { - this.ref = 0; - } - else { - this.ref = newRef; - } - return this.ref.toString(); - } - /** - * Unsubscribe from channels with the specified topic. - * - * @internal - */ - _leaveOpenTopic(topic) { - let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); - if (dupChannel) { - this.log('transport', `leaving duplicate topic "${topic}"`); - dupChannel.unsubscribe(); - } - } - /** - * Removes a subscription from the socket. - * - * @param channel An open subscription. - * - * @internal - */ - _remove(channel) { - this.channels = this.channels.filter((c) => c._joinRef() !== channel._joinRef()); - } - /** - * Sets up connection handlers. - * - * @internal - */ - setupConnection() { - if (this.conn) { - this.conn.binaryType = 'arraybuffer'; - this.conn.onopen = () => this._onConnOpen(); - this.conn.onerror = (error) => this._onConnError(error); - this.conn.onmessage = (event) => this._onConnMessage(event); - this.conn.onclose = (event) => this._onConnClose(event); - } - } - /** - * Returns the URL of the websocket. - * - * @internal - */ - _endPointURL() { - return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: VSN })); - } - /** @internal */ - _onConnMessage(rawMessage) { - this.decode(rawMessage.data, (msg) => { - let { topic, event, payload, ref } = msg; - if ((ref && ref === this.pendingHeartbeatRef) || - event === (payload === null || payload === void 0 ? void 0 : payload.type)) { - this.pendingHeartbeatRef = null; - } - this.log('receive', `${payload.status || ''} ${topic} ${event} ${(ref && '(' + ref + ')') || ''}`, payload); - this.channels - .filter((channel) => channel._isMember(topic)) - .forEach((channel) => channel._trigger(event, payload, ref)); - this.stateChangeCallbacks.message.forEach((callback) => callback(msg)); - }); - } - /** @internal */ - _onConnOpen() { - this.log('transport', `connected to ${this._endPointURL()}`); - this._flushSendBuffer(); - this.reconnectTimer.reset(); - this.heartbeatTimer && clearInterval(this.heartbeatTimer); - this.heartbeatTimer = setInterval(() => this._sendHeartbeat(), this.heartbeatIntervalMs); - this.stateChangeCallbacks.open.forEach((callback) => callback()); - } - /** @internal */ - _onConnClose(event) { - this.log('transport', 'close', event); - this._triggerChanError(); - this.heartbeatTimer && clearInterval(this.heartbeatTimer); - this.reconnectTimer.scheduleTimeout(); - this.stateChangeCallbacks.close.forEach((callback) => callback(event)); - } - /** @internal */ - _onConnError(error) { - this.log('transport', error.message); - this._triggerChanError(); - this.stateChangeCallbacks.error.forEach((callback) => callback(error)); - } - /** @internal */ - _triggerChanError() { - this.channels.forEach((channel) => channel._trigger(CHANNEL_EVENTS.error)); - } - /** @internal */ - _appendParams(url, params) { - if (Object.keys(params).length === 0) { - return url; - } - const prefix = url.match(/\?/) ? '&' : '?'; - const query = new URLSearchParams(params); - return `${url}${prefix}${query}`; - } - /** @internal */ - _flushSendBuffer() { - if (this.isConnected() && this.sendBuffer.length > 0) { - this.sendBuffer.forEach((callback) => callback()); - this.sendBuffer = []; - } - } - /** @internal */ - _sendHeartbeat() { - var _a; - if (!this.isConnected()) { - return; - } - if (this.pendingHeartbeatRef) { - this.pendingHeartbeatRef = null; - this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); - (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(WS_CLOSE_NORMAL, 'hearbeat timeout'); - return; - } - this.pendingHeartbeatRef = this._makeRef(); - this.push({ - topic: 'phoenix', - event: 'heartbeat', - payload: {}, - ref: this.pendingHeartbeatRef, - }); - this.setAuth(this.accessToken); - } - } - class WSWebSocketDummy { - constructor(address, _protocols, options) { - this.binaryType = 'arraybuffer'; - this.onclose = () => { }; - this.onerror = () => { }; - this.onmessage = () => { }; - this.onopen = () => { }; - this.readyState = SOCKET_STATES.connecting; - this.send = () => { }; - this.url = null; - this.url = address; - this.close = options.close; - } - } - - 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; - } - - function toByteArray(b64) { - if (!inited) { - init(); - } - 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"); - } - - // 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 = - 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 = 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); - } - - // 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; - } - } - 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 (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding'); - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - - 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); - } - - 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); - } - return that; - } - - function fromObject(that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that; - } - - obj.copy(that, 0, 0, len); - return that; - } - - 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 (obj.type === "Buffer" && isArray(obj.data)) { - return fromArrayLike(that, obj.data); - } - } - - 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); - } - - 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(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); - - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - - // 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; - } - - 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"); - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - 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"); - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - 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"); - } - 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 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); - }; - - 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; - }; - - 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 ""; - }; - - Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError("Argument must be a Buffer"); - } - - 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; - } - 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); - } - - // 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() - } - - // 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; - } - - 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); - } - 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 ret; - } - - 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; - 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 < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - - 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; - }; - - /* - * 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 val; - }; - - Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val; - }; - - 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(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)); - } - - class StorageError extends Error { - constructor(message) { - super(message); - this.__isStorageError = true; - this.name = 'StorageError'; - } - } - function isStorageError(error) { - return typeof error === 'object' && error !== null && '__isStorageError' in error; - } - class StorageApiError extends StorageError { - constructor(message, status) { - super(message); - this.name = 'StorageApiError'; - this.status = status; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - }; - } - } - class StorageUnknownError extends StorageError { - constructor(message, originalError) { - super(message); - this.name = 'StorageUnknownError'; - this.originalError = originalError; - } - } - - var __awaiter$6 = (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()); - }); - }; - const resolveFetch$2 = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - const resolveResponse = () => __awaiter$6(void 0, void 0, void 0, function* () { - if (typeof Response === 'undefined') { - // @ts-ignore - return (yield Promise.resolve().then(function () { return browser; })).Response; - } - return Response; - }); - const recursiveToCamel = (item) => { - if (Array.isArray(item)) { - return item.map((el) => recursiveToCamel(el)); - } - else if (typeof item === 'function' || item !== Object(item)) { - return item; - } - const result = {}; - Object.entries(item).forEach(([key, value]) => { - const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')); - result[newKey] = recursiveToCamel(value); - }); - return result; - }; - - var __awaiter$5 = (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()); - }); - }; - const _getErrorMessage$1 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); - const handleError$1 = (error, reject, options) => __awaiter$5(void 0, void 0, void 0, function* () { - const Res = yield resolveResponse(); - if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { - error - .json() - .then((err) => { - reject(new StorageApiError(_getErrorMessage$1(err), error.status || 500)); - }) - .catch((err) => { - reject(new StorageUnknownError(_getErrorMessage$1(err), err)); - }); - } - else { - reject(new StorageUnknownError(_getErrorMessage$1(error), error)); - } - }); - const _getRequestParams$1 = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET') { - return params; - } - params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); - if (body) { - params.body = JSON.stringify(body); - } - return Object.assign(Object.assign({}, params), parameters); - }; - function _handleRequest$1(fetcher, method, url, options, parameters, body) { - return __awaiter$5(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - fetcher(url, _getRequestParams$1(method, options, parameters, body)) - .then((result) => { - if (!result.ok) - throw result; - if (options === null || options === void 0 ? void 0 : options.noResolveJson) - return result; - return result.json(); - }) - .then((data) => resolve(data)) - .catch((error) => handleError$1(error, reject, options)); - }); - }); - } - function get(fetcher, url, options, parameters) { - return __awaiter$5(this, void 0, void 0, function* () { - return _handleRequest$1(fetcher, 'GET', url, options, parameters); - }); - } - function post(fetcher, url, body, options, parameters) { - return __awaiter$5(this, void 0, void 0, function* () { - return _handleRequest$1(fetcher, 'POST', url, options, parameters, body); - }); - } - function put(fetcher, url, body, options, parameters) { - return __awaiter$5(this, void 0, void 0, function* () { - return _handleRequest$1(fetcher, 'PUT', url, options, parameters, body); - }); - } - function head(fetcher, url, options, parameters) { - return __awaiter$5(this, void 0, void 0, function* () { - return _handleRequest$1(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); - }); - } - function remove(fetcher, url, body, options, parameters) { - return __awaiter$5(this, void 0, void 0, function* () { - return _handleRequest$1(fetcher, 'DELETE', url, options, parameters, body); - }); - } - - var __awaiter$4 = (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()); - }); - }; - const DEFAULT_SEARCH_OPTIONS = { - limit: 100, - offset: 0, - sortBy: { - column: 'name', - order: 'asc', - }, - }; - const DEFAULT_FILE_OPTIONS = { - cacheControl: '3600', - contentType: 'text/plain;charset=UTF-8', - upsert: false, - }; - class StorageFileApi { - constructor(url, headers = {}, bucketId, fetch) { - this.url = url; - this.headers = headers; - this.bucketId = bucketId; - this.fetch = resolveFetch$2(fetch); - } - /** - * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. - * - * @param method HTTP method. - * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param fileBody The body of the file to be stored in the bucket. - */ - uploadOrUpdate(method, path, fileBody, fileOptions) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - let body; - const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); - let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); - const metadata = options.metadata; - if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { - body = new FormData(); - body.append('cacheControl', options.cacheControl); - body.append('', fileBody); - if (metadata) { - body.append('metadata', this.encodeMetadata(metadata)); - } - } - else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { - body = fileBody; - body.append('cacheControl', options.cacheControl); - if (metadata) { - body.append('metadata', this.encodeMetadata(metadata)); - } - } - else { - body = fileBody; - headers['cache-control'] = `max-age=${options.cacheControl}`; - headers['content-type'] = options.contentType; - if (metadata) { - headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata)); - } - } - if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { - headers = Object.assign(Object.assign({}, headers), fileOptions.headers); - } - const cleanPath = this._removeEmptyFolders(path); - const _path = this._getFinalPath(cleanPath); - const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body: body, headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); - const data = yield res.json(); - if (res.ok) { - return { - data: { path: cleanPath, id: data.Id, fullPath: data.Key }, - error: null, - }; - } - else { - const error = data; - return { data: null, error }; - } - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Uploads a file to an existing bucket. - * - * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param fileBody The body of the file to be stored in the bucket. - */ - upload(path, fileBody, fileOptions) { - return __awaiter$4(this, void 0, void 0, function* () { - return this.uploadOrUpdate('POST', path, fileBody, fileOptions); - }); - } - /** - * Upload a file with a token generated from `createSignedUploadUrl`. - * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param token The token generated from `createSignedUploadUrl` - * @param fileBody The body of the file to be stored in the bucket. - */ - uploadToSignedUrl(path, token, fileBody, fileOptions) { - return __awaiter$4(this, void 0, void 0, function* () { - const cleanPath = this._removeEmptyFolders(path); - const _path = this._getFinalPath(cleanPath); - const url = new URL(this.url + `/object/upload/sign/${_path}`); - url.searchParams.set('token', token); - try { - let body; - const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); - const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); - if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { - body = new FormData(); - body.append('cacheControl', options.cacheControl); - body.append('', fileBody); - } - else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { - body = fileBody; - body.append('cacheControl', options.cacheControl); - } - else { - body = fileBody; - headers['cache-control'] = `max-age=${options.cacheControl}`; - headers['content-type'] = options.contentType; - } - const res = yield this.fetch(url.toString(), { - method: 'PUT', - body: body, - headers, - }); - const data = yield res.json(); - if (res.ok) { - return { - data: { path: cleanPath, fullPath: data.Key }, - error: null, - }; - } - else { - const error = data; - return { data: null, error }; - } - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a signed upload URL. - * Signed upload URLs can be used to upload files to the bucket without further authentication. - * They are valid for 2 hours. - * @param path The file path, including the current file name. For example `folder/image.png`. - * @param options.upsert If set to true, allows the file to be overwritten if it already exists. - */ - createSignedUploadUrl(path, options) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - let _path = this._getFinalPath(path); - const headers = Object.assign({}, this.headers); - if (options === null || options === void 0 ? void 0 : options.upsert) { - headers['x-upsert'] = 'true'; - } - const data = yield post(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); - const url = new URL(this.url + data.url); - const token = url.searchParams.get('token'); - if (!token) { - throw new StorageError('No token returned by API'); - } - return { data: { signedUrl: url.toString(), path, token }, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Replaces an existing file at the specified path with a new one. - * - * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. - * @param fileBody The body of the file to be stored in the bucket. - */ - update(path, fileBody, fileOptions) { - return __awaiter$4(this, void 0, void 0, function* () { - return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); - }); - } - /** - * Moves an existing file to a new path in the same bucket. - * - * @param fromPath The original file path, including the current file name. For example `folder/image.png`. - * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. - * @param options The destination options. - */ - move(fromPath, toPath, options) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - const data = yield post(this.fetch, `${this.url}/object/move`, { - bucketId: this.bucketId, - sourceKey: fromPath, - destinationKey: toPath, - destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Copies an existing file to a new path in the same bucket. - * - * @param fromPath The original file path, including the current file name. For example `folder/image.png`. - * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. - * @param options The destination options. - */ - copy(fromPath, toPath, options) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - const data = yield post(this.fetch, `${this.url}/object/copy`, { - bucketId: this.bucketId, - sourceKey: fromPath, - destinationKey: toPath, - destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, - }, { headers: this.headers }); - return { data: { path: data.Key }, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. - * - * @param path The file path, including the current file name. For example `folder/image.png`. - * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. - * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - * @param options.transform Transform the asset before serving it to the client. - */ - createSignedUrl(path, expiresIn, options) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - let _path = this._getFinalPath(path); - let data = yield post(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `&download=${options.download === true ? '' : options.download}` - : ''; - const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); - data = { signedUrl }; - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. - * - * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. - * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. - * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - */ - createSignedUrls(paths, expiresIn, options) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - const data = yield post(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `&download=${options.download === true ? '' : options.download}` - : ''; - return { - data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL - ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) - : null }))), - error: null, - }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. - * - * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. - * @param options.transform Transform the asset before serving it to the client. - */ - download(path, options) { - return __awaiter$4(this, void 0, void 0, function* () { - const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; - const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; - const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); - const queryString = transformationQuery ? `?${transformationQuery}` : ''; - try { - const _path = this._getFinalPath(path); - const res = yield get(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { - headers: this.headers, - noResolveJson: true, - }); - const data = yield res.blob(); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves the details of an existing file. - * @param path - */ - info(path) { - return __awaiter$4(this, void 0, void 0, function* () { - const _path = this._getFinalPath(path); - try { - const data = yield get(this.fetch, `${this.url}/object/info/${_path}`, { - headers: this.headers, - }); - return { data: recursiveToCamel(data), error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Checks the existence of a file. - * @param path - */ - exists(path) { - return __awaiter$4(this, void 0, void 0, function* () { - const _path = this._getFinalPath(path); - try { - yield head(this.fetch, `${this.url}/object/${_path}`, { - headers: this.headers, - }); - return { data: true, error: null }; - } - catch (error) { - if (isStorageError(error) && error instanceof StorageUnknownError) { - const originalError = error.originalError; - if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { - return { data: false, error }; - } - } - throw error; - } - }); - } - /** - * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. - * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. - * - * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. - * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - * @param options.transform Transform the asset before serving it to the client. - */ - getPublicUrl(path, options) { - const _path = this._getFinalPath(path); - const _queryString = []; - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `download=${options.download === true ? '' : options.download}` - : ''; - if (downloadQueryParam !== '') { - _queryString.push(downloadQueryParam); - } - const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; - const renderPath = wantsTransformation ? 'render/image' : 'object'; - const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); - if (transformationQuery !== '') { - _queryString.push(transformationQuery); - } - let queryString = _queryString.join('&'); - if (queryString !== '') { - queryString = `?${queryString}`; - } - return { - data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, - }; - } - /** - * Deletes files within the same bucket - * - * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. - */ - remove(paths) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - const data = yield remove(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Get file metadata - * @param id the file id to retrieve metadata - */ - // async getMetadata( - // id: string - // ): Promise< - // | { - // data: Metadata - // error: null - // } - // | { - // data: null - // error: StorageError - // } - // > { - // try { - // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) - // return { data, error: null } - // } catch (error) { - // if (isStorageError(error)) { - // return { data: null, error } - // } - // throw error - // } - // } - /** - * Update file metadata - * @param id the file id to update metadata - * @param meta the new file metadata - */ - // async updateMetadata( - // id: string, - // meta: Metadata - // ): Promise< - // | { - // data: Metadata - // error: null - // } - // | { - // data: null - // error: StorageError - // } - // > { - // try { - // const data = await post( - // this.fetch, - // `${this.url}/metadata/${id}`, - // { ...meta }, - // { headers: this.headers } - // ) - // return { data, error: null } - // } catch (error) { - // if (isStorageError(error)) { - // return { data: null, error } - // } - // throw error - // } - // } - /** - * Lists all the files within a bucket. - * @param path The folder path. - */ - list(path, options, parameters) { - return __awaiter$4(this, void 0, void 0, function* () { - try { - const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); - const data = yield post(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - encodeMetadata(metadata) { - return JSON.stringify(metadata); - } - toBase64(data) { - if (typeof Buffer !== 'undefined') { - return Buffer.from(data).toString('base64'); - } - return btoa(data); - } - _getFinalPath(path) { - return `${this.bucketId}/${path}`; - } - _removeEmptyFolders(path) { - return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); - } - transformOptsToQueryString(transform) { - const params = []; - if (transform.width) { - params.push(`width=${transform.width}`); - } - if (transform.height) { - params.push(`height=${transform.height}`); - } - if (transform.resize) { - params.push(`resize=${transform.resize}`); - } - if (transform.format) { - params.push(`format=${transform.format}`); - } - if (transform.quality) { - params.push(`quality=${transform.quality}`); - } - return params.join('&'); - } - } - - // generated by genversion - const version$2 = '2.7.0'; - - const DEFAULT_HEADERS$2 = { 'X-Client-Info': `storage-js/${version$2}` }; - - var __awaiter$3 = (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()); - }); - }; - class StorageBucketApi { - constructor(url, headers = {}, fetch) { - this.url = url; - this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS$2), headers); - this.fetch = resolveFetch$2(fetch); - } - /** - * Retrieves the details of all Storage buckets within an existing project. - */ - listBuckets() { - return __awaiter$3(this, void 0, void 0, function* () { - try { - const data = yield get(this.fetch, `${this.url}/bucket`, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves the details of an existing Storage bucket. - * - * @param id The unique identifier of the bucket you would like to retrieve. - */ - getBucket(id) { - return __awaiter$3(this, void 0, void 0, function* () { - try { - const data = yield get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a new Storage bucket - * - * @param id A unique identifier for the bucket you are creating. - * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. - * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. - * The global file size limit takes precedence over this value. - * The default value is null, which doesn't set a per bucket file size limit. - * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. - * The default value is null, which allows files with all mime types to be uploaded. - * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. - * @returns newly created bucket id - */ - createBucket(id, options = { - public: false, - }) { - return __awaiter$3(this, void 0, void 0, function* () { - try { - const data = yield post(this.fetch, `${this.url}/bucket`, { - id, - name: id, - public: options.public, - file_size_limit: options.fileSizeLimit, - allowed_mime_types: options.allowedMimeTypes, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Updates a Storage bucket - * - * @param id A unique identifier for the bucket you are updating. - * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. - * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. - * The global file size limit takes precedence over this value. - * The default value is null, which doesn't set a per bucket file size limit. - * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. - * The default value is null, which allows files with all mime types to be uploaded. - * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. - */ - updateBucket(id, options) { - return __awaiter$3(this, void 0, void 0, function* () { - try { - const data = yield put(this.fetch, `${this.url}/bucket/${id}`, { - id, - name: id, - public: options.public, - file_size_limit: options.fileSizeLimit, - allowed_mime_types: options.allowedMimeTypes, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Removes all objects inside a single bucket. - * - * @param id The unique identifier of the bucket you would like to empty. - */ - emptyBucket(id) { - return __awaiter$3(this, void 0, void 0, function* () { - try { - const data = yield post(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. - * You must first `empty()` the bucket. - * - * @param id The unique identifier of the bucket you would like to delete. - */ - deleteBucket(id) { - return __awaiter$3(this, void 0, void 0, function* () { - try { - const data = yield remove(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (isStorageError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - } - - class StorageClient extends StorageBucketApi { - constructor(url, headers = {}, fetch) { - super(url, headers, fetch); - } - /** - * Perform file operation in a bucket. - * - * @param id The bucket id to operate on. - */ - from(id) { - return new StorageFileApi(this.url, this.headers, id, this.fetch); - } - } - - const version$1 = '2.45.3'; - - let JS_ENV = ''; - // @ts-ignore - if (typeof Deno !== 'undefined') { - JS_ENV = 'deno'; - } - else if (typeof document !== 'undefined') { - JS_ENV = 'web'; - } - else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { - JS_ENV = 'react-native'; - } - else { - JS_ENV = 'node'; - } - const DEFAULT_HEADERS$1 = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version$1}` }; - const DEFAULT_GLOBAL_OPTIONS = { - headers: DEFAULT_HEADERS$1, - }; - const DEFAULT_DB_OPTIONS = { - schema: 'public', - }; - const DEFAULT_AUTH_OPTIONS = { - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true, - flowType: 'implicit', - }; - const DEFAULT_REALTIME_OPTIONS = {}; - - var __awaiter$2 = (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()); - }); - }; - const resolveFetch$1 = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = nodeFetch; - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - const resolveHeadersConstructor = () => { - if (typeof Headers === 'undefined') { - return Headers$1; - } - return Headers; - }; - const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { - const fetch = resolveFetch$1(customFetch); - const HeadersConstructor = resolveHeadersConstructor(); - return (input, init) => __awaiter$2(void 0, void 0, void 0, function* () { - var _a; - const accessToken = (_a = (yield getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; - let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); - if (!headers.has('apikey')) { - headers.set('apikey', supabaseKey); - } - if (!headers.has('Authorization')) { - headers.set('Authorization', `Bearer ${accessToken}`); - } - return fetch(input, Object.assign(Object.assign({}, init), { headers })); - }); - }; - - 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()); - }); - }; - function stripTrailingSlash(url) { - return url.replace(/\/$/, ''); - } - function applySettingDefaults(options, defaults) { - const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; - const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; - const result = { - db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), - auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), - realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), - global: Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), - accessToken: () => __awaiter$1(this, void 0, void 0, function* () { return ''; }), - }; - if (options.accessToken) { - result.accessToken = options.accessToken; - } - else { - // hack around Required<> - delete result.accessToken; - } - return result; - } - - const version = '2.65.0'; - - const GOTRUE_URL = 'http://localhost:9999'; - const STORAGE_KEY = 'supabase.auth.token'; - const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` }; - const EXPIRY_MARGIN = 10; // in seconds - const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; - const API_VERSIONS = { - '2024-01-01': { - timestamp: Date.parse('2024-01-01T00:00:00.0Z'), - name: '2024-01-01', - }, - }; - - function expiresAt(expiresIn) { - const timeNow = Math.round(Date.now() / 1000); - return timeNow + expiresIn; - } - function uuid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); - } - const isBrowser = () => typeof document !== 'undefined'; - const localStorageWriteTests = { - tested: false, - writable: false, - }; - /** - * Checks whether localStorage is supported on this browser. - */ - const supportsLocalStorage = () => { - if (!isBrowser()) { - return false; - } - try { - if (typeof globalThis.localStorage !== 'object') { - return false; - } - } - catch (e) { - // DOM exception when accessing `localStorage` - return false; - } - if (localStorageWriteTests.tested) { - return localStorageWriteTests.writable; - } - const randomKey = `lswt-${Math.random()}${Math.random()}`; - try { - globalThis.localStorage.setItem(randomKey, randomKey); - globalThis.localStorage.removeItem(randomKey); - localStorageWriteTests.tested = true; - localStorageWriteTests.writable = true; - } - catch (e) { - // localStorage can't be written to - // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document - localStorageWriteTests.tested = true; - localStorageWriteTests.writable = false; - } - return localStorageWriteTests.writable; - }; - /** - * Extracts parameters encoded in the URL both in the query and fragment. - */ - function parseParametersFromURL(href) { - const result = {}; - const url = new URL(href); - if (url.hash && url.hash[0] === '#') { - try { - const hashSearchParams = new URLSearchParams(url.hash.substring(1)); - hashSearchParams.forEach((value, key) => { - result[key] = value; - }); - } - catch (e) { - // hash is not a query string - } - } - // search parameters take precedence over hash parameters - url.searchParams.forEach((value, key) => { - result[key] = value; - }); - return result; - } - const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - const looksLikeFetchResponse = (maybeResponse) => { - return (typeof maybeResponse === 'object' && - maybeResponse !== null && - 'status' in maybeResponse && - 'ok' in maybeResponse && - 'json' in maybeResponse && - typeof maybeResponse.json === 'function'); - }; - // Storage helpers - const setItemAsync = async (storage, key, data) => { - await storage.setItem(key, JSON.stringify(data)); - }; - const getItemAsync = async (storage, key) => { - const value = await storage.getItem(key); - if (!value) { - return null; - } - try { - return JSON.parse(value); - } - catch (_a) { - return value; - } - }; - const removeItemAsync = async (storage, key) => { - await storage.removeItem(key); - }; - function decodeBase64URL(value) { - const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - let base64 = ''; - let chr1, chr2, chr3; - let enc1, enc2, enc3, enc4; - let i = 0; - value = value.replace('-', '+').replace('_', '/'); - while (i < value.length) { - enc1 = key.indexOf(value.charAt(i++)); - enc2 = key.indexOf(value.charAt(i++)); - enc3 = key.indexOf(value.charAt(i++)); - enc4 = key.indexOf(value.charAt(i++)); - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; - base64 = base64 + String.fromCharCode(chr1); - if (enc3 != 64 && chr2 != 0) { - base64 = base64 + String.fromCharCode(chr2); - } - if (enc4 != 64 && chr3 != 0) { - base64 = base64 + String.fromCharCode(chr3); - } - } - return base64; - } - /** - * A deferred represents some asynchronous work that is not yet finished, which - * may or may not culminate in a value. - * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts - */ - class Deferred { - constructor() { - this.promise = new Deferred.promiseConstructor((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - Deferred.promiseConstructor = Promise; - // Taken from: https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library - function decodeJWTPayload(token) { - // Regex checks for base64url format - const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i; - const parts = token.split('.'); - if (parts.length !== 3) { - throw new Error('JWT is not valid: not a JWT structure'); - } - if (!base64UrlRegex.test(parts[1])) { - throw new Error('JWT is not valid: payload is not in base64url format'); - } - const base64Url = parts[1]; - return JSON.parse(decodeBase64URL(base64Url)); - } - /** - * Creates a promise that resolves to null after some time. - */ - async function sleep(time) { - return await new Promise((accept) => { - setTimeout(() => accept(null), time); - }); - } - /** - * Converts the provided async function into a retryable function. Each result - * or thrown error is sent to the isRetryable function which should return true - * if the function should run again. - */ - function retryable(fn, isRetryable) { - const promise = new Promise((accept, reject) => { - (async () => { - for (let attempt = 0; attempt < Infinity; attempt++) { - try { - const result = await fn(attempt); - if (!isRetryable(attempt, null, result)) { - accept(result); - return; - } - } - catch (e) { - if (!isRetryable(attempt, e)) { - reject(e); - return; - } - } - } - })(); - }); - return promise; - } - function dec2hex(dec) { - return ('0' + dec.toString(16)).substr(-2); - } - // Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs - function generatePKCEVerifier() { - const verifierLength = 56; - const array = new Uint32Array(verifierLength); - if (typeof crypto === 'undefined') { - const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; - const charSetLen = charSet.length; - let verifier = ''; - for (let i = 0; i < verifierLength; i++) { - verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); - } - return verifier; - } - crypto.getRandomValues(array); - return Array.from(array, dec2hex).join(''); - } - async function sha256(randomString) { - const encoder = new TextEncoder(); - const encodedData = encoder.encode(randomString); - const hash = await crypto.subtle.digest('SHA-256', encodedData); - const bytes = new Uint8Array(hash); - return Array.from(bytes) - .map((c) => String.fromCharCode(c)) - .join(''); - } - function base64urlencode(str) { - return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); - } - async function generatePKCEChallenge(verifier) { - const hasCryptoSupport = typeof crypto !== 'undefined' && - typeof crypto.subtle !== 'undefined' && - typeof TextEncoder !== 'undefined'; - if (!hasCryptoSupport) { - console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); - return verifier; - } - const hashed = await sha256(verifier); - return base64urlencode(hashed); - } - async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { - const codeVerifier = generatePKCEVerifier(); - let storedCodeVerifier = codeVerifier; - if (isPasswordRecovery) { - storedCodeVerifier += '/PASSWORD_RECOVERY'; - } - await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier); - const codeChallenge = await generatePKCEChallenge(codeVerifier); - const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; - return [codeChallenge, codeChallengeMethod]; - } - /** Parses the API version which is 2YYY-MM-DD. */ - const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; - function parseResponseAPIVersion(response) { - const apiVersion = response.headers.get(API_VERSION_HEADER_NAME); - if (!apiVersion) { - return null; - } - if (!apiVersion.match(API_VERSION_REGEX)) { - return null; - } - try { - const date = new Date(`${apiVersion}T00:00:00.0Z`); - return date; - } - catch (e) { - return null; - } - } - - class AuthError extends Error { - constructor(message, status, code) { - super(message); - this.__isAuthError = true; - this.name = 'AuthError'; - this.status = status; - this.code = code; - } - } - function isAuthError(error) { - return typeof error === 'object' && error !== null && '__isAuthError' in error; - } - class AuthApiError extends AuthError { - constructor(message, status, code) { - super(message, status, code); - this.name = 'AuthApiError'; - this.status = status; - this.code = code; - } - } - function isAuthApiError(error) { - return isAuthError(error) && error.name === 'AuthApiError'; - } - class AuthUnknownError extends AuthError { - constructor(message, originalError) { - super(message); - this.name = 'AuthUnknownError'; - this.originalError = originalError; - } - } - class CustomAuthError extends AuthError { - constructor(message, name, status, code) { - super(message, status, code); - this.name = name; - this.status = status; - } - } - class AuthSessionMissingError extends CustomAuthError { - constructor() { - super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); - } - } - function isAuthSessionMissingError(error) { - return isAuthError(error) && error.name === 'AuthSessionMissingError'; - } - class AuthInvalidTokenResponseError extends CustomAuthError { - constructor() { - super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); - } - } - class AuthInvalidCredentialsError extends CustomAuthError { - constructor(message) { - super(message, 'AuthInvalidCredentialsError', 400, undefined); - } - } - class AuthImplicitGrantRedirectError extends CustomAuthError { - constructor(message, details = null) { - super(message, 'AuthImplicitGrantRedirectError', 500, undefined); - this.details = null; - this.details = details; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - details: this.details, - }; - } - } - class AuthPKCEGrantCodeExchangeError extends CustomAuthError { - constructor(message, details = null) { - super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); - this.details = null; - this.details = details; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - details: this.details, - }; - } - } - class AuthRetryableFetchError extends CustomAuthError { - constructor(message, status) { - super(message, 'AuthRetryableFetchError', status, undefined); - } - } - function isAuthRetryableFetchError(error) { - return isAuthError(error) && error.name === 'AuthRetryableFetchError'; - } - /** - * This error is thrown on certain methods when the password used is deemed - * weak. Inspect the reasons to identify what password strength rules are - * inadequate. - */ - class AuthWeakPasswordError extends CustomAuthError { - constructor(message, status, reasons) { - super(message, 'AuthWeakPasswordError', status, 'weak_password'); - this.reasons = reasons; - } - } - function isAuthWeakPasswordError(error) { - return isAuthError(error) && error.name === 'AuthWeakPasswordError'; - } - - var __rest$1 = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); - const NETWORK_ERROR_CODES = [502, 503, 504]; - async function handleError(error) { - var _a; - if (!looksLikeFetchResponse(error)) { - throw new AuthRetryableFetchError(_getErrorMessage(error), 0); - } - if (NETWORK_ERROR_CODES.includes(error.status)) { - // status in 500...599 range - server had an error, request might be retryed. - throw new AuthRetryableFetchError(_getErrorMessage(error), error.status); - } - let data; - try { - data = await error.json(); - } - catch (e) { - throw new AuthUnknownError(_getErrorMessage(e), e); - } - let errorCode = undefined; - const responseAPIVersion = parseResponseAPIVersion(error); - if (responseAPIVersion && - responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp && - typeof data === 'object' && - data && - typeof data.code === 'string') { - errorCode = data.code; - } - else if (typeof data === 'object' && data && typeof data.error_code === 'string') { - errorCode = data.error_code; - } - if (!errorCode) { - // Legacy support for weak password errors, when there were no error codes - if (typeof data === 'object' && - data && - typeof data.weak_password === 'object' && - data.weak_password && - Array.isArray(data.weak_password.reasons) && - data.weak_password.reasons.length && - data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { - throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); - } - } - else if (errorCode === 'weak_password') { - throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); - } - else if (errorCode === 'session_not_found') { - // The `session_id` inside the JWT does not correspond to a row in the - // `sessions` table. This usually means the user has signed out, has been - // deleted, or their session has somehow been terminated. - throw new AuthSessionMissingError(); - } - throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); - } - const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET') { - return params; - } - params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - return Object.assign(Object.assign({}, params), parameters); - }; - async function _request(fetcher, method, url, options) { - var _a; - const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); - if (!headers[API_VERSION_HEADER_NAME]) { - headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name; - } - if (options === null || options === void 0 ? void 0 : options.jwt) { - headers['Authorization'] = `Bearer ${options.jwt}`; - } - const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; - if (options === null || options === void 0 ? void 0 : options.redirectTo) { - qs['redirect_to'] = options.redirectTo; - } - const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; - const data = await _handleRequest(fetcher, method, url + queryString, { - headers, - noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, - }, {}, options === null || options === void 0 ? void 0 : options.body); - return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; - } - async function _handleRequest(fetcher, method, url, options, parameters, body) { - const requestParams = _getRequestParams(method, options, parameters, body); - let result; - try { - result = await fetcher(url, Object.assign({}, requestParams)); - } - catch (e) { - console.error(e); - // fetch failed, likely due to a network or CORS error - throw new AuthRetryableFetchError(_getErrorMessage(e), 0); - } - if (!result.ok) { - await handleError(result); - } - if (options === null || options === void 0 ? void 0 : options.noResolveJson) { - return result; - } - try { - return await result.json(); - } - catch (e) { - await handleError(e); - } - } - function _sessionResponse(data) { - var _a; - let session = null; - if (hasSession(data)) { - session = Object.assign({}, data); - if (!data.expires_at) { - session.expires_at = expiresAt(data.expires_in); - } - } - const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; - return { data: { session, user }, error: null }; - } - function _sessionResponsePassword(data) { - const response = _sessionResponse(data); - if (!response.error && - data.weak_password && - typeof data.weak_password === 'object' && - Array.isArray(data.weak_password.reasons) && - data.weak_password.reasons.length && - data.weak_password.message && - typeof data.weak_password.message === 'string' && - data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { - response.data.weak_password = data.weak_password; - } - return response; - } - function _userResponse(data) { - var _a; - const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; - return { data: { user }, error: null }; - } - function _ssoResponse(data) { - return { data, error: null }; - } - function _generateLinkResponse(data) { - const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest$1(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); - const properties = { - action_link, - email_otp, - hashed_token, - redirect_to, - verification_type, - }; - const user = Object.assign({}, rest); - return { - data: { - properties, - user, - }, - error: null, - }; - } - function _noResolveJsonResponse(data) { - return data; - } - /** - * hasSession checks if the response object contains a valid session - * @param data A response object - * @returns true if a session is in the response - */ - function hasSession(data) { - return data.access_token && data.refresh_token && data.expires_in; - } - - var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - class GoTrueAdminApi { - constructor({ url = '', headers = {}, fetch, }) { - this.url = url; - this.headers = headers; - this.fetch = resolveFetch(fetch); - this.mfa = { - listFactors: this._listFactors.bind(this), - deleteFactor: this._deleteFactor.bind(this), - }; - } - /** - * Removes a logged-in session. - * @param jwt A valid, logged-in JWT. - * @param scope The logout sope. - */ - async signOut(jwt, scope = 'global') { - try { - await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { - headers: this.headers, - jwt, - noResolveJson: true, - }); - return { data: null, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Sends an invite link to an email address. - * @param email The email address of the user. - * @param options Additional options to be included when inviting. - */ - async inviteUserByEmail(email, options = {}) { - try { - return await _request(this.fetch, 'POST', `${this.url}/invite`, { - body: { email, data: options.data }, - headers: this.headers, - redirectTo: options.redirectTo, - xform: _userResponse, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Generates email links and OTPs to be sent via a custom email provider. - * @param email The user's email. - * @param options.password User password. For signup only. - * @param options.data Optional user metadata. For signup only. - * @param options.redirectTo The redirect url which should be appended to the generated link - */ - async generateLink(params) { - try { - const { options } = params, rest = __rest(params, ["options"]); - const body = Object.assign(Object.assign({}, rest), options); - if ('newEmail' in rest) { - // replace newEmail with new_email in request body - body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; - delete body['newEmail']; - } - return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, { - body: body, - headers: this.headers, - xform: _generateLinkResponse, - redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, - }); - } - catch (error) { - if (isAuthError(error)) { - return { - data: { - properties: null, - user: null, - }, - error, - }; - } - throw error; - } - } - // User Admin API - /** - * Creates a new user. - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async createUser(attributes) { - try { - return await _request(this.fetch, 'POST', `${this.url}/admin/users`, { - body: attributes, - headers: this.headers, - xform: _userResponse, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Get a list of users. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. - */ - async listUsers(params) { - var _a, _b, _c, _d, _e, _f, _g; - try { - const pagination = { nextPage: null, lastPage: 0, total: 0 }; - const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, { - headers: this.headers, - noResolveJson: true, - query: { - page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', - per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', - }, - xform: _noResolveJsonResponse, - }); - if (response.error) - throw response.error; - const users = await response.json(); - const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; - const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; - if (links.length > 0) { - links.forEach((link) => { - const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); - const rel = JSON.parse(link.split(';')[1].split('=')[1]); - pagination[`${rel}Page`] = page; - }); - pagination.total = parseInt(total); - } - return { data: Object.assign(Object.assign({}, users), pagination), error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { users: [] }, error }; - } - throw error; - } - } - /** - * Get user by id. - * - * @param uid The user's unique identifier - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async getUserById(uid) { - try { - return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { - headers: this.headers, - xform: _userResponse, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Updates the user data. - * - * @param attributes The data you want to update. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async updateUserById(uid, attributes) { - try { - return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { - body: attributes, - headers: this.headers, - xform: _userResponse, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Delete a user. Requires a `service_role` key. - * - * @param id The user id you want to remove. - * @param shouldSoftDelete If true, then the user will be soft-deleted (setting `deleted_at` to the current timestamp and disabling their account while preserving their data) from the auth schema. - * Defaults to false for backward compatibility. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async deleteUser(id, shouldSoftDelete = false) { - try { - return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { - headers: this.headers, - body: { - should_soft_delete: shouldSoftDelete, - }, - xform: _userResponse, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - async _listFactors(params) { - try { - const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { - headers: this.headers, - xform: (factors) => { - return { data: { factors }, error: null }; - }, - }); - return { data, error }; - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - async _deleteFactor(params) { - try { - const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - } - - /** - * Provides safe access to the globalThis.localStorage property. - */ - const localStorageAdapter = { - getItem: (key) => { - if (!supportsLocalStorage()) { - return null; - } - return globalThis.localStorage.getItem(key); - }, - setItem: (key, value) => { - if (!supportsLocalStorage()) { - return; - } - globalThis.localStorage.setItem(key, value); - }, - removeItem: (key) => { - if (!supportsLocalStorage()) { - return; - } - globalThis.localStorage.removeItem(key); - }, - }; - /** - * Returns a localStorage-like object that stores the key-value pairs in - * memory. - */ - function memoryLocalStorageAdapter(store = {}) { - return { - getItem: (key) => { - return store[key] || null; - }, - setItem: (key, value) => { - store[key] = value; - }, - removeItem: (key) => { - delete store[key]; - }, - }; - } - - /** - * https://mathiasbynens.be/notes/globalthis - */ - function polyfillGlobalThis() { - if (typeof globalThis === 'object') - return; - try { - Object.defineProperty(Object.prototype, '__magic__', { - get: function () { - return this; - }, - configurable: true, - }); - // @ts-expect-error 'Allow access to magic' - __magic__.globalThis = __magic__; - // @ts-expect-error 'Allow access to magic' - delete Object.prototype.__magic__; - } - catch (e) { - if (typeof self !== 'undefined') { - // @ts-expect-error 'Allow access to globals' - self.globalThis = self; - } - } - } - - /** - * @experimental - */ - const internals = { - /** - * @experimental - */ - debug: !!(globalThis && - supportsLocalStorage() && - globalThis.localStorage && - globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), - }; - /** - * An error thrown when a lock cannot be acquired after some amount of time. - * - * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. - */ - class LockAcquireTimeoutError extends Error { - constructor(message) { - super(message); - this.isAcquireTimeout = true; - } - } - class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { - } - /** - * Implements a global exclusive lock using the Navigator LockManager API. It - * is available on all browsers released after 2022-03-15 with Safari being the - * last one to release support. If the API is not available, this function will - * throw. Make sure you check availablility before configuring {@link - * GoTrueClient}. - * - * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` - * local storage item to `true`. - * - * Internals: - * - * Since the LockManager API does not preserve stack traces for the async - * function passed in the `request` method, a trick is used where acquiring the - * lock releases a previously started promise to run the operation in the `fn` - * function. The lock waits for that promise to finish (with or without error), - * while the function will finally wait for the result anyway. - * - * @param name Name of the lock to be acquired. - * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if - * the lock can't be acquired without waiting. If positive, the lock acquire - * will time out after so many milliseconds. An error is - * a timeout if it has `isAcquireTimeout` set to true. - * @param fn The operation to run once the lock is acquired. - */ - async function navigatorLock(name, acquireTimeout, fn) { - if (internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); - } - const abortController = new globalThis.AbortController(); - if (acquireTimeout > 0) { - setTimeout(() => { - abortController.abort(); - if (internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); - } - }, acquireTimeout); - } - // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request - return await globalThis.navigator.locks.request(name, acquireTimeout === 0 - ? { - mode: 'exclusive', - ifAvailable: true, - } - : { - mode: 'exclusive', - signal: abortController.signal, - }, async (lock) => { - if (lock) { - if (internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); - } - try { - return await fn(); - } - finally { - if (internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); - } - } - } - else { - if (acquireTimeout === 0) { - if (internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); - } - throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); - } - else { - if (internals.debug) { - try { - const result = await globalThis.navigator.locks.query(); - console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); - } - catch (e) { - console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); - } - } - // Browser is not following the Navigator LockManager spec, it - // returned a null lock when we didn't use ifAvailable. So we can - // pretend the lock is acquired in the name of backward compatibility - // and user experience and just run the function. - console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); - return await fn(); - } - } - }); - } - - polyfillGlobalThis(); // Make "globalThis" available - const DEFAULT_OPTIONS = { - url: GOTRUE_URL, - storageKey: STORAGE_KEY, - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true, - headers: DEFAULT_HEADERS, - flowType: 'implicit', - debug: false, - hasCustomAuthorizationHeader: false, - }; - /** Current session will be checked for refresh at this interval. */ - const AUTO_REFRESH_TICK_DURATION = 30 * 1000; - /** - * A token refresh will be attempted this many ticks before the current session expires. */ - const AUTO_REFRESH_TICK_THRESHOLD = 3; - async function lockNoOp(name, acquireTimeout, fn) { - return await fn(); - } - class GoTrueClient { - /** - * Create a new client for use in the browser. - */ - constructor(options) { - var _a, _b; - this.memoryStorage = null; - this.stateChangeEmitters = new Map(); - this.autoRefreshTicker = null; - this.visibilityChangedCallback = null; - this.refreshingDeferred = null; - /** - * Keeps track of the async client initialization. - * When null or not yet resolved the auth state is `unknown` - * Once resolved the the auth state is known and it's save to call any further client methods. - * Keep extra care to never reject or throw uncaught errors - */ - this.initializePromise = null; - this.detectSessionInUrl = true; - this.hasCustomAuthorizationHeader = false; - this.suppressGetSessionWarning = false; - this.lockAcquired = false; - this.pendingInLock = []; - /** - * Used to broadcast state change events to other tabs listening. - */ - this.broadcastChannel = null; - this.logger = console.log; - this.instanceID = GoTrueClient.nextInstanceID; - GoTrueClient.nextInstanceID += 1; - if (this.instanceID > 0 && isBrowser()) { - console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); - } - const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); - this.logDebugMessages = !!settings.debug; - if (typeof settings.debug === 'function') { - this.logger = settings.debug; - } - this.persistSession = settings.persistSession; - this.storageKey = settings.storageKey; - this.autoRefreshToken = settings.autoRefreshToken; - this.admin = new GoTrueAdminApi({ - url: settings.url, - headers: settings.headers, - fetch: settings.fetch, - }); - this.url = settings.url; - this.headers = settings.headers; - this.fetch = resolveFetch(settings.fetch); - this.lock = settings.lock || lockNoOp; - this.detectSessionInUrl = settings.detectSessionInUrl; - this.flowType = settings.flowType; - this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; - if (settings.lock) { - this.lock = settings.lock; - } - else if (isBrowser() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) { - this.lock = navigatorLock; - } - else { - this.lock = lockNoOp; - } - this.mfa = { - verify: this._verify.bind(this), - enroll: this._enroll.bind(this), - unenroll: this._unenroll.bind(this), - challenge: this._challenge.bind(this), - listFactors: this._listFactors.bind(this), - challengeAndVerify: this._challengeAndVerify.bind(this), - getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), - }; - if (this.persistSession) { - if (settings.storage) { - this.storage = settings.storage; - } - else { - if (supportsLocalStorage()) { - this.storage = localStorageAdapter; - } - else { - this.memoryStorage = {}; - this.storage = memoryLocalStorageAdapter(this.memoryStorage); - } - } - } - else { - this.memoryStorage = {}; - this.storage = memoryLocalStorageAdapter(this.memoryStorage); - } - if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { - try { - this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); - } - catch (e) { - console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); - } - (_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => { - this._debug('received broadcast notification from other tab or client', event); - await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages - }); - } - this.initialize(); - } - _debug(...args) { - if (this.logDebugMessages) { - this.logger(`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, ...args); - } - return this; - } - /** - * Initializes the client session either from the url or from storage. - * This method is automatically called when instantiating the client, but should also be called - * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). - */ - async initialize() { - if (this.initializePromise) { - return await this.initializePromise; - } - this.initializePromise = (async () => { - return await this._acquireLock(-1, async () => { - return await this._initialize(); - }); - })(); - return await this.initializePromise; - } - /** - * IMPORTANT: - * 1. Never throw in this method, as it is called from the constructor - * 2. Never return a session from this method as it would be cached over - * the whole lifetime of the client - */ - async _initialize() { - try { - const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false; - this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow); - if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) { - const { data, error } = await this._getSessionFromURL(isPKCEFlow); - if (error) { - this._debug('#_initialize()', 'error detecting session from URL', error); - // hacky workaround to keep the existing session if there's an error returned from identity linking - // TODO: once error codes are ready, we should match against it instead of the message - if ((error === null || error === void 0 ? void 0 : error.message) === 'Identity is already linked' || - (error === null || error === void 0 ? void 0 : error.message) === 'Identity is already linked to another user') { - return { error }; - } - // failed login attempt via url, - // remove old session as in verifyOtp, signUp and signInWith* - await this._removeSession(); - return { error }; - } - const { session, redirectType } = data; - this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); - await this._saveSession(session); - setTimeout(async () => { - if (redirectType === 'recovery') { - await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); - } - else { - await this._notifyAllSubscribers('SIGNED_IN', session); - } - }, 0); - return { error: null }; - } - // no login attempt via callback url try to recover session from storage - await this._recoverAndRefresh(); - return { error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { error }; - } - return { - error: new AuthUnknownError('Unexpected error during initialization', error), - }; - } - finally { - await this._handleVisibilityChange(); - this._debug('#_initialize()', 'end'); - } - } - /** - * Creates a new anonymous user. - * - * @returns A session where the is_anonymous claim in the access token JWT set to true - */ - async signInAnonymously(credentials) { - var _a, _b, _c; - try { - const res = await _request(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - body: { - data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, - gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, - }, - xform: _sessionResponse, - }); - const { data, error } = res; - if (error || !data) { - return { data: { user: null, session: null }, error: error }; - } - const session = data.session; - const user = data.user; - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Creates a new user. - * - * Be aware that if a user account exists in the system you may get back an - * error message that attempts to hide this information from the user. - * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. - * - * @returns A logged-in session if the server has "autoconfirm" ON - * @returns A user if the server has "autoconfirm" OFF - */ - async signUp(credentials) { - var _a, _b, _c; - try { - let res; - if ('email' in credentials) { - const { email, password, options } = credentials; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); - } - res = await _request(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - body: { - email, - password, - data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - }, - xform: _sessionResponse, - }); - } - else if ('phone' in credentials) { - const { phone, password, options } = credentials; - res = await _request(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - body: { - phone, - password, - data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, - channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: _sessionResponse, - }); - } - else { - throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); - } - const { data, error } = res; - if (error || !data) { - return { data: { user: null, session: null }, error: error }; - } - const session = data.session; - const user = data.user; - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in an existing user with an email and password or phone and password. - * - * Be aware that you may get back an error message that will not distinguish - * between the cases where the account does not exist or that the - * email/phone and password combination is wrong or that the account can only - * be accessed via social login. - */ - async signInWithPassword(credentials) { - try { - let res; - if ('email' in credentials) { - const { email, password, options } = credentials; - res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { - headers: this.headers, - body: { - email, - password, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: _sessionResponsePassword, - }); - } - else if ('phone' in credentials) { - const { phone, password, options } = credentials; - res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { - headers: this.headers, - body: { - phone, - password, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: _sessionResponsePassword, - }); - } - else { - throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); - } - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { - data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), - error, - }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in an existing user via a third-party provider. - * This method supports the PKCE flow. - */ - async signInWithOAuth(credentials) { - var _a, _b, _c, _d; - return await this._handleProviderSignIn(credentials.provider, { - redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, - scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, - queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, - skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, - }); - } - /** - * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. - */ - async exchangeCodeForSession(authCode) { - await this.initializePromise; - return this._acquireLock(-1, async () => { - return this._exchangeCodeForSession(authCode); - }); - } - async _exchangeCodeForSession(authCode) { - const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); - const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); - try { - const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { - headers: this.headers, - body: { - auth_code: authCode, - code_verifier: codeVerifier, - }, - xform: _sessionResponse, - }); - await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null, redirectType: null }, - error: new AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null, redirectType: null }, error }; - } - throw error; - } - } - /** - * Allows signing in with an OIDC ID token. The authentication provider used - * should be enabled and configured. - */ - async signInWithIdToken(credentials) { - try { - const { options, provider, token, access_token, nonce } = credentials; - const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { - headers: this.headers, - body: { - provider, - id_token: token, - access_token, - nonce, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: _sessionResponse, - }); - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data, error }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in a user using magiclink or a one-time password (OTP). - * - * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. - * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. - * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. - * - * Be aware that you may get back an error message that will not distinguish - * between the cases where the account does not exist or, that the account - * can only be accessed via social login. - * - * Do note that you will need to configure a Whatsapp sender on Twilio - * if you are using phone sign in with the 'whatsapp' channel. The whatsapp - * channel is not supported on other providers - * at this time. - * This method supports PKCE when an email is passed. - */ - async signInWithOtp(credentials) { - var _a, _b, _c, _d, _e; - try { - if ('email' in credentials) { - const { email, options } = credentials; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); - } - const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { - headers: this.headers, - body: { - email, - data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, - create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - }, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - }); - return { data: { user: null, session: null }, error }; - } - if ('phone' in credentials) { - const { phone, options } = credentials; - const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { - headers: this.headers, - body: { - phone, - data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, - create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', - }, - }); - return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; - } - throw new AuthInvalidCredentialsError('You must provide either an email or phone number.'); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in a user given a User supplied OTP or TokenHash received through mobile or email. - */ - async verifyOtp(params) { - var _a, _b; - try { - let redirectTo = undefined; - let captchaToken = undefined; - if ('options' in params) { - redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; - captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; - } - const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { - headers: this.headers, - body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), - redirectTo, - xform: _sessionResponse, - }); - if (error) { - throw error; - } - if (!data) { - throw new Error('An error occurred on token verification.'); - } - const session = data.session; - const user = data.user; - if (session === null || session === void 0 ? void 0 : session.access_token) { - await this._saveSession(session); - await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Attempts a single-sign on using an enterprise Identity Provider. A - * successful SSO attempt will redirect the current page to the identity - * provider authorization page. The redirect URL is implementation and SSO - * protocol specific. - * - * You can use it by providing a SSO domain. Typically you can extract this - * domain by asking users for their email address. If this domain is - * registered on the Auth instance the redirect will use that organization's - * currently active SSO Identity Provider for the login. - * - * If you have built an organization-specific login page, you can use the - * organization's SSO Identity Provider UUID directly instead. - */ - async signInWithSSO(params) { - var _a, _b, _c; - try { - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); - } - return await _request(this.fetch, 'POST', `${this.url}/sso`, { - body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) - ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } - : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), - headers: this.headers, - xform: _ssoResponse, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Sends a reauthentication OTP to the user's email or phone number. - * Requires the user to be signed-in. - */ - async reauthenticate() { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._reauthenticate(); - }); - } - async _reauthenticate() { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) - throw sessionError; - if (!session) - throw new AuthSessionMissingError(); - const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { - headers: this.headers, - jwt: session.access_token, - }); - return { data: { user: null, session: null }, error }; - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. - */ - async resend(credentials) { - try { - const endpoint = `${this.url}/resend`; - if ('email' in credentials) { - const { email, type, options } = credentials; - const { error } = await _request(this.fetch, 'POST', endpoint, { - headers: this.headers, - body: { - email, - type, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - }); - return { data: { user: null, session: null }, error }; - } - else if ('phone' in credentials) { - const { phone, type, options } = credentials; - const { data, error } = await _request(this.fetch, 'POST', endpoint, { - headers: this.headers, - body: { - phone, - type, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - }); - return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; - } - throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Returns the session, refreshing it if necessary. - * - * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. - * - * **IMPORTANT:** This method loads values directly from the storage attached - * to the client. If that storage is based on request cookies for example, - * the values in it may not be authentic and therefore it's strongly advised - * against using this method and its results in such circumstances. A warning - * will be emitted if this is detected. Use {@link #getUser()} instead. - */ - async getSession() { - await this.initializePromise; - const result = await this._acquireLock(-1, async () => { - return this._useSession(async (result) => { - return result; - }); - }); - return result; - } - /** - * Acquires a global lock based on the storage key. - */ - async _acquireLock(acquireTimeout, fn) { - this._debug('#_acquireLock', 'begin', acquireTimeout); - try { - if (this.lockAcquired) { - const last = this.pendingInLock.length - ? this.pendingInLock[this.pendingInLock.length - 1] - : Promise.resolve(); - const result = (async () => { - await last; - return await fn(); - })(); - this.pendingInLock.push((async () => { - try { - await result; - } - catch (e) { - // we just care if it finished - } - })()); - return result; - } - return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { - this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); - try { - this.lockAcquired = true; - const result = fn(); - this.pendingInLock.push((async () => { - try { - await result; - } - catch (e) { - // we just care if it finished - } - })()); - await result; - // keep draining the queue until there's nothing to wait on - while (this.pendingInLock.length) { - const waitOn = [...this.pendingInLock]; - await Promise.all(waitOn); - this.pendingInLock.splice(0, waitOn.length); - } - return await result; - } - finally { - this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); - this.lockAcquired = false; - } - }); - } - finally { - this._debug('#_acquireLock', 'end'); - } - } - /** - * Use instead of {@link #getSession} inside the library. It is - * semantically usually what you want, as getting a session involves some - * processing afterwards that requires only one client operating on the - * session at once across multiple tabs or processes. - */ - async _useSession(fn) { - this._debug('#_useSession', 'begin'); - try { - // the use of __loadSession here is the only correct use of the function! - const result = await this.__loadSession(); - return await fn(result); - } - finally { - this._debug('#_useSession', 'end'); - } - } - /** - * NEVER USE DIRECTLY! - * - * Always use {@link #_useSession}. - */ - async __loadSession() { - this._debug('#__loadSession()', 'begin'); - if (!this.lockAcquired) { - this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); - } - try { - let currentSession = null; - const maybeSession = await getItemAsync(this.storage, this.storageKey); - this._debug('#getSession()', 'session from storage', maybeSession); - if (maybeSession !== null) { - if (this._isValidSession(maybeSession)) { - currentSession = maybeSession; - } - else { - this._debug('#getSession()', 'session from storage is not valid'); - await this._removeSession(); - } - } - if (!currentSession) { - return { data: { session: null }, error: null }; - } - const hasExpired = currentSession.expires_at - ? currentSession.expires_at <= Date.now() / 1000 - : false; - this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); - if (!hasExpired) { - if (this.storage.isServer) { - let suppressWarning = this.suppressGetSessionWarning; - const proxySession = new Proxy(currentSession, { - get: (target, prop, receiver) => { - if (!suppressWarning && prop === 'user') { - // only show warning when the user object is being accessed from the server - console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); - suppressWarning = true; // keeps this proxy instance from logging additional warnings - this.suppressGetSessionWarning = true; // keeps this client's future proxy instances from warning - } - return Reflect.get(target, prop, receiver); - }, - }); - currentSession = proxySession; - } - return { data: { session: currentSession }, error: null }; - } - const { session, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { session: null }, error }; - } - return { data: { session }, error: null }; - } - finally { - this._debug('#__loadSession()', 'end'); - } - } - /** - * Gets the current user details if there is an existing session. This method - * performs a network request to the Supabase Auth server, so the returned - * value is authentic and can be used to base authorization rules on. - * - * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. - */ - async getUser(jwt) { - if (jwt) { - return await this._getUser(jwt); - } - await this.initializePromise; - const result = await this._acquireLock(-1, async () => { - return await this._getUser(); - }); - return result; - } - async _getUser(jwt) { - try { - if (jwt) { - return await _request(this.fetch, 'GET', `${this.url}/user`, { - headers: this.headers, - jwt: jwt, - xform: _userResponse, - }); - } - return await this._useSession(async (result) => { - var _a, _b, _c; - const { data, error } = result; - if (error) { - throw error; - } - // returns an error if there is no access_token or custom authorization header - if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { - return { data: { user: null }, error: new AuthSessionMissingError() }; - } - return await _request(this.fetch, 'GET', `${this.url}/user`, { - headers: this.headers, - jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, - xform: _userResponse, - }); - }); - } - catch (error) { - if (isAuthError(error)) { - if (isAuthSessionMissingError(error)) { - // JWT contains a `session_id` which does not correspond to an active - // session in the database, indicating the user is signed out. - await this._removeSession(); - await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); - await this._notifyAllSubscribers('SIGNED_OUT', null); - } - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Updates user data for a logged in user. - */ - async updateUser(attributes, options = {}) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._updateUser(attributes, options); - }); - } - async _updateUser(attributes, options = {}) { - try { - return await this._useSession(async (result) => { - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - throw sessionError; - } - if (!sessionData.session) { - throw new AuthSessionMissingError(); - } - const session = sessionData.session; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce' && attributes.email != null) { - ; - [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); - } - const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { - headers: this.headers, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), - jwt: session.access_token, - xform: _userResponse, - }); - if (userError) - throw userError; - session.user = data.user; - await this._saveSession(session); - await this._notifyAllSubscribers('USER_UPDATED', session); - return { data: { user: session.user }, error: null }; - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Decodes a JWT (without performing any validation). - */ - _decodeJWT(jwt) { - return decodeJWTPayload(jwt); - } - /** - * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. - * If the refresh token or access token in the current session is invalid, an error will be thrown. - * @param currentSession The current session that minimally contains an access token and refresh token. - */ - async setSession(currentSession) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._setSession(currentSession); - }); - } - async _setSession(currentSession) { - try { - if (!currentSession.access_token || !currentSession.refresh_token) { - throw new AuthSessionMissingError(); - } - const timeNow = Date.now() / 1000; - let expiresAt = timeNow; - let hasExpired = true; - let session = null; - const payload = decodeJWTPayload(currentSession.access_token); - if (payload.exp) { - expiresAt = payload.exp; - hasExpired = expiresAt <= timeNow; - } - if (hasExpired) { - const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { user: null, session: null }, error: error }; - } - if (!refreshedSession) { - return { data: { user: null, session: null }, error: null }; - } - session = refreshedSession; - } - else { - const { data, error } = await this._getUser(currentSession.access_token); - if (error) { - throw error; - } - session = { - access_token: currentSession.access_token, - refresh_token: currentSession.refresh_token, - user: data.user, - token_type: 'bearer', - expires_in: expiresAt - timeNow, - expires_at: expiresAt, - }; - await this._saveSession(session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user: session.user, session }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { session: null, user: null }, error }; - } - throw error; - } - } - /** - * Returns a new session, regardless of expiry status. - * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). - * If the current session's refresh token is invalid, an error will be thrown. - * @param currentSession The current session. If passed in, it must contain a refresh token. - */ - async refreshSession(currentSession) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._refreshSession(currentSession); - }); - } - async _refreshSession(currentSession) { - try { - return await this._useSession(async (result) => { - var _a; - if (!currentSession) { - const { data, error } = result; - if (error) { - throw error; - } - currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; - } - if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { - throw new AuthSessionMissingError(); - } - const { session, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { user: null, session: null }, error: error }; - } - if (!session) { - return { data: { user: null, session: null }, error: null }; - } - return { data: { user: session.user, session }, error: null }; - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Gets the session data from a URL string - */ - async _getSessionFromURL(isPKCEFlow) { - try { - if (!isBrowser()) - throw new AuthImplicitGrantRedirectError('No browser detected.'); - if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) { - throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); - } - else if (this.flowType == 'pkce' && !isPKCEFlow) { - throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); - } - const params = parseParametersFromURL(window.location.href); - if (isPKCEFlow) { - if (!params.code) - throw new AuthPKCEGrantCodeExchangeError('No code detected.'); - const { data, error } = await this._exchangeCodeForSession(params.code); - if (error) - throw error; - const url = new URL(window.location.href); - url.searchParams.delete('code'); - window.history.replaceState(window.history.state, '', url.toString()); - return { data: { session: data.session, redirectType: null }, error: null }; - } - if (params.error || params.error_description || params.error_code) { - throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { - error: params.error || 'unspecified_error', - code: params.error_code || 'unspecified_code', - }); - } - const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; - if (!access_token || !expires_in || !refresh_token || !token_type) { - throw new AuthImplicitGrantRedirectError('No session defined in URL'); - } - const timeNow = Math.round(Date.now() / 1000); - const expiresIn = parseInt(expires_in); - let expiresAt = timeNow + expiresIn; - if (expires_at) { - expiresAt = parseInt(expires_at); - } - const actuallyExpiresIn = expiresAt - timeNow; - if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION) { - console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); - } - const issuedAt = expiresAt - expiresIn; - if (timeNow - issuedAt >= 120) { - console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); - } - else if (timeNow - issuedAt < 0) { - console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); - } - const { data, error } = await this._getUser(access_token); - if (error) - throw error; - const session = { - provider_token, - provider_refresh_token, - access_token, - expires_in: expiresIn, - expires_at: expiresAt, - refresh_token, - token_type, - user: data.user, - }; - // Remove tokens from URL - window.location.hash = ''; - this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); - return { data: { session, redirectType: params.type }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { session: null, redirectType: null }, error }; - } - throw error; - } - } - /** - * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) - */ - _isImplicitGrantFlow() { - const params = parseParametersFromURL(window.location.href); - return !!(isBrowser() && (params.access_token || params.error_description)); - } - /** - * Checks if the current URL and backing storage contain parameters given by a PKCE flow - */ - async _isPKCEFlow() { - const params = parseParametersFromURL(window.location.href); - const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); - return !!(params.code && currentStorageContent); - } - /** - * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. - * - * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. - * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. - * - * If using `others` scope, no `SIGNED_OUT` event is fired! - */ - async signOut(options = { scope: 'global' }) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._signOut(options); - }); - } - async _signOut({ scope } = { scope: 'global' }) { - return await this._useSession(async (result) => { - var _a; - const { data, error: sessionError } = result; - if (sessionError) { - return { error: sessionError }; - } - const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; - if (accessToken) { - const { error } = await this.admin.signOut(accessToken, scope); - if (error) { - // ignore 404s since user might not exist anymore - // ignore 401s since an invalid or expired JWT should sign out the current session - if (!(isAuthApiError(error) && - (error.status === 404 || error.status === 401 || error.status === 403))) { - return { error }; - } - } - } - if (scope !== 'others') { - await this._removeSession(); - await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); - await this._notifyAllSubscribers('SIGNED_OUT', null); - } - return { error: null }; - }); - } - /** - * Receive a notification every time an auth event happens. - * @param callback A callback function to be invoked when an auth event happens. - */ - onAuthStateChange(callback) { - const id = uuid(); - const subscription = { - id, - callback, - unsubscribe: () => { - this._debug('#unsubscribe()', 'state change callback with id removed', id); - this.stateChangeEmitters.delete(id); - }, - }; - this._debug('#onAuthStateChange()', 'registered callback with id', id); - this.stateChangeEmitters.set(id, subscription); - (async () => { - await this.initializePromise; - await this._acquireLock(-1, async () => { - this._emitInitialSession(id); - }); - })(); - return { data: { subscription } }; - } - async _emitInitialSession(id) { - return await this._useSession(async (result) => { - var _a, _b; - try { - const { data: { session }, error, } = result; - if (error) - throw error; - await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); - this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); - } - catch (err) { - await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); - this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); - console.error(err); - } - }); - } - /** - * Sends a password reset request to an email address. This method supports the PKCE flow. - * - * @param email The email address of the user. - * @param options.redirectTo The URL to send the user to after they click the password reset link. - * @param options.captchaToken Verification token received when the user completes the captcha on the site. - */ - async resetPasswordForEmail(email, options = {}) { - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey, true // isPasswordRecovery - ); - } - try { - return await _request(this.fetch, 'POST', `${this.url}/recover`, { - body: { - email, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - gotrue_meta_security: { captcha_token: options.captchaToken }, - }, - headers: this.headers, - redirectTo: options.redirectTo, - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Gets all the identities linked to a user. - */ - async getUserIdentities() { - var _a; - try { - const { data, error } = await this.getUser(); - if (error) - throw error; - return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Links an oauth identity to an existing user. - * This method supports the PKCE flow. - */ - async linkIdentity(credentials) { - var _a; - try { - const { data, error } = await this._useSession(async (result) => { - var _a, _b, _c, _d, _e; - const { data, error } = result; - if (error) - throw error; - const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { - redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, - scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, - queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, - skipBrowserRedirect: true, - }); - return await _request(this.fetch, 'GET', url, { - headers: this.headers, - jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, - }); - }); - if (error) - throw error; - if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { - window.location.assign(data === null || data === void 0 ? void 0 : data.url); - } - return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null }; - } - catch (error) { - if (isAuthError(error)) { - return { data: { provider: credentials.provider, url: null }, error }; - } - throw error; - } - } - /** - * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. - */ - async unlinkIdentity(identity) { - try { - return await this._useSession(async (result) => { - var _a, _b; - const { data, error } = result; - if (error) { - throw error; - } - return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { - headers: this.headers, - jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, - }); - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Generates a new JWT. - * @param refreshToken A valid refresh token that was returned on login. - */ - async _refreshAccessToken(refreshToken) { - const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; - this._debug(debugName, 'begin'); - try { - const startedAt = Date.now(); - // will attempt to refresh the token with exponential backoff - return await retryable(async (attempt) => { - if (attempt > 0) { - await sleep(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... - } - this._debug(debugName, 'refreshing attempt', attempt); - return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { - body: { refresh_token: refreshToken }, - headers: this.headers, - xform: _sessionResponse, - }); - }, (attempt, error) => { - const nextBackOffInterval = 200 * Math.pow(2, attempt); - return (error && - isAuthRetryableFetchError(error) && - // retryable only if the request can be sent before the backoff overflows the tick duration - Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION); - }); - } - catch (error) { - this._debug(debugName, 'error', error); - if (isAuthError(error)) { - return { data: { session: null, user: null }, error }; - } - throw error; - } - finally { - this._debug(debugName, 'end'); - } - } - _isValidSession(maybeSession) { - const isValidSession = typeof maybeSession === 'object' && - maybeSession !== null && - 'access_token' in maybeSession && - 'refresh_token' in maybeSession && - 'expires_at' in maybeSession; - return isValidSession; - } - async _handleProviderSignIn(provider, options) { - const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { - redirectTo: options.redirectTo, - scopes: options.scopes, - queryParams: options.queryParams, - }); - this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); - // try to open on the browser - if (isBrowser() && !options.skipBrowserRedirect) { - window.location.assign(url); - } - return { data: { provider, url }, error: null }; - } - /** - * Recovers the session from LocalStorage and refreshes - * Note: this method is async to accommodate for AsyncStorage e.g. in React native. - */ - async _recoverAndRefresh() { - var _a; - const debugName = '#_recoverAndRefresh()'; - this._debug(debugName, 'begin'); - try { - const currentSession = await getItemAsync(this.storage, this.storageKey); - this._debug(debugName, 'session from storage', currentSession); - if (!this._isValidSession(currentSession)) { - this._debug(debugName, 'session is not valid'); - if (currentSession !== null) { - await this._removeSession(); - } - return; - } - const timeNow = Math.round(Date.now() / 1000); - const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN; - this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN}s`); - if (expiresWithMargin) { - if (this.autoRefreshToken && currentSession.refresh_token) { - const { error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - console.error(error); - if (!isAuthRetryableFetchError(error)) { - this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); - await this._removeSession(); - } - } - } - } - else { - // no need to persist currentSession again, as we just loaded it from - // local storage; persisting it again may overwrite a value saved by - // another client with access to the same local storage - await this._notifyAllSubscribers('SIGNED_IN', currentSession); - } - } - catch (err) { - this._debug(debugName, 'error', err); - console.error(err); - return; - } - finally { - this._debug(debugName, 'end'); - } - } - async _callRefreshToken(refreshToken) { - var _a, _b; - if (!refreshToken) { - throw new AuthSessionMissingError(); - } - // refreshing is already in progress - if (this.refreshingDeferred) { - return this.refreshingDeferred.promise; - } - const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; - this._debug(debugName, 'begin'); - try { - this.refreshingDeferred = new Deferred(); - const { data, error } = await this._refreshAccessToken(refreshToken); - if (error) - throw error; - if (!data.session) - throw new AuthSessionMissingError(); - await this._saveSession(data.session); - await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); - const result = { session: data.session, error: null }; - this.refreshingDeferred.resolve(result); - return result; - } - catch (error) { - this._debug(debugName, 'error', error); - if (isAuthError(error)) { - const result = { session: null, error }; - if (!isAuthRetryableFetchError(error)) { - await this._removeSession(); - await this._notifyAllSubscribers('SIGNED_OUT', null); - } - (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); - return result; - } - (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); - throw error; - } - finally { - this.refreshingDeferred = null; - this._debug(debugName, 'end'); - } - } - async _notifyAllSubscribers(event, session, broadcast = true) { - const debugName = `#_notifyAllSubscribers(${event})`; - this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); - try { - if (this.broadcastChannel && broadcast) { - this.broadcastChannel.postMessage({ event, session }); - } - const errors = []; - const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { - try { - await x.callback(event, session); - } - catch (e) { - errors.push(e); - } - }); - await Promise.all(promises); - if (errors.length > 0) { - for (let i = 0; i < errors.length; i += 1) { - console.error(errors[i]); - } - throw errors[0]; - } - } - finally { - this._debug(debugName, 'end'); - } - } - /** - * set currentSession and currentUser - * process to _startAutoRefreshToken if possible - */ - async _saveSession(session) { - this._debug('#_saveSession()', session); - // _saveSession is always called whenever a new session has been acquired - // so we can safely suppress the warning returned by future getSession calls - this.suppressGetSessionWarning = true; - await setItemAsync(this.storage, this.storageKey, session); - } - async _removeSession() { - this._debug('#_removeSession()'); - await removeItemAsync(this.storage, this.storageKey); - } - /** - * Removes any registered visibilitychange callback. - * - * {@see #startAutoRefresh} - * {@see #stopAutoRefresh} - */ - _removeVisibilityChangedCallback() { - this._debug('#_removeVisibilityChangedCallback()'); - const callback = this.visibilityChangedCallback; - this.visibilityChangedCallback = null; - try { - if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { - window.removeEventListener('visibilitychange', callback); - } - } - catch (e) { - console.error('removing visibilitychange callback failed', e); - } - } - /** - * This is the private implementation of {@link #startAutoRefresh}. Use this - * within the library. - */ - async _startAutoRefresh() { - await this._stopAutoRefresh(); - this._debug('#_startAutoRefresh()'); - const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION); - this.autoRefreshTicker = ticker; - if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { - // ticker is a NodeJS Timeout object that has an `unref` method - // https://nodejs.org/api/timers.html#timeoutunref - // When auto refresh is used in NodeJS (like for testing) the - // `setInterval` is preventing the process from being marked as - // finished and tests run endlessly. This can be prevented by calling - // `unref()` on the returned object. - ticker.unref(); - // @ts-ignore - } - else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { - // similar like for NodeJS, but with the Deno API - // https://deno.land/api@latest?unstable&s=Deno.unrefTimer - // @ts-ignore - Deno.unrefTimer(ticker); - } - // run the tick immediately, but in the next pass of the event loop so that - // #_initialize can be allowed to complete without recursively waiting on - // itself - setTimeout(async () => { - await this.initializePromise; - await this._autoRefreshTokenTick(); - }, 0); - } - /** - * This is the private implementation of {@link #stopAutoRefresh}. Use this - * within the library. - */ - async _stopAutoRefresh() { - this._debug('#_stopAutoRefresh()'); - const ticker = this.autoRefreshTicker; - this.autoRefreshTicker = null; - if (ticker) { - clearInterval(ticker); - } - } - /** - * Starts an auto-refresh process in the background. The session is checked - * every few seconds. Close to the time of expiration a process is started to - * refresh the session. If refreshing fails it will be retried for as long as - * necessary. - * - * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need - * to call this function, it will be called for you. - * - * On browsers the refresh process works only when the tab/window is in the - * foreground to conserve resources as well as prevent race conditions and - * flooding auth with requests. If you call this method any managed - * visibility change callback will be removed and you must manage visibility - * changes on your own. - * - * On non-browser platforms the refresh process works *continuously* in the - * background, which may not be desirable. You should hook into your - * platform's foreground indication mechanism and call these methods - * appropriately to conserve resources. - * - * {@see #stopAutoRefresh} - */ - async startAutoRefresh() { - this._removeVisibilityChangedCallback(); - await this._startAutoRefresh(); - } - /** - * Stops an active auto refresh process running in the background (if any). - * - * If you call this method any managed visibility change callback will be - * removed and you must manage visibility changes on your own. - * - * See {@link #startAutoRefresh} for more details. - */ - async stopAutoRefresh() { - this._removeVisibilityChangedCallback(); - await this._stopAutoRefresh(); - } - /** - * Runs the auto refresh token tick. - */ - async _autoRefreshTokenTick() { - this._debug('#_autoRefreshTokenTick()', 'begin'); - try { - await this._acquireLock(0, async () => { - try { - const now = Date.now(); - try { - return await this._useSession(async (result) => { - const { data: { session }, } = result; - if (!session || !session.refresh_token || !session.expires_at) { - this._debug('#_autoRefreshTokenTick()', 'no session'); - return; - } - // session will expire in this many ticks (or has already expired if <= 0) - const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION); - this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`); - if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { - await this._callRefreshToken(session.refresh_token); - } - }); - } - catch (e) { - console.error('Auto refresh tick failed with error. This is likely a transient error.', e); - } - } - finally { - this._debug('#_autoRefreshTokenTick()', 'end'); - } - }); - } - catch (e) { - if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) { - this._debug('auto refresh token tick lock not available'); - } - else { - throw e; - } - } - } - /** - * Registers callbacks on the browser / platform, which in-turn run - * algorithms when the browser window/tab are in foreground. On non-browser - * platforms it assumes always foreground. - */ - async _handleVisibilityChange() { - this._debug('#_handleVisibilityChange()'); - if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { - if (this.autoRefreshToken) { - // in non-browser environments the refresh token ticker runs always - this.startAutoRefresh(); - } - return false; - } - try { - this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); - window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); - // now immediately call the visbility changed callback to setup with the - // current visbility state - await this._onVisibilityChanged(true); // initial call - } - catch (error) { - console.error('_handleVisibilityChange', error); - } - } - /** - * Callback registered with `window.addEventListener('visibilitychange')`. - */ - async _onVisibilityChanged(calledFromInitialize) { - const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; - this._debug(methodName, 'visibilityState', document.visibilityState); - if (document.visibilityState === 'visible') { - if (this.autoRefreshToken) { - // in browser environments the refresh token ticker runs only on focused tabs - // which prevents race conditions - this._startAutoRefresh(); - } - if (!calledFromInitialize) { - // called when the visibility has changed, i.e. the browser - // transitioned from hidden -> visible so we need to see if the session - // should be recovered immediately... but to do that we need to acquire - // the lock first asynchronously - await this.initializePromise; - await this._acquireLock(-1, async () => { - if (document.visibilityState !== 'visible') { - this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); - // visibility has changed while waiting for the lock, abort - return; - } - // recover the session - await this._recoverAndRefresh(); - }); - } - } - else if (document.visibilityState === 'hidden') { - if (this.autoRefreshToken) { - this._stopAutoRefresh(); - } - } - } - /** - * Generates the relevant login URL for a third-party provider. - * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. - * @param options.scopes A space-separated list of scopes granted to the OAuth application. - * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. - */ - async _getUrlForProvider(url, provider, options) { - const urlParams = [`provider=${encodeURIComponent(provider)}`]; - if (options === null || options === void 0 ? void 0 : options.redirectTo) { - urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); - } - if (options === null || options === void 0 ? void 0 : options.scopes) { - urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); - } - if (this.flowType === 'pkce') { - const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); - const flowParams = new URLSearchParams({ - code_challenge: `${encodeURIComponent(codeChallenge)}`, - code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, - }); - urlParams.push(flowParams.toString()); - } - if (options === null || options === void 0 ? void 0 : options.queryParams) { - const query = new URLSearchParams(options.queryParams); - urlParams.push(query.toString()); - } - if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { - urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); - } - return `${url}?${urlParams.join('&')}`; - } - async _unenroll(params) { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * {@see GoTrueMFAApi#enroll} - */ - async _enroll(params) { - try { - return await this._useSession(async (result) => { - var _a, _b; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' ? { phone: params.phone } : { issuer: params.issuer })); - const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, { - body, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - if (error) { - return { data: null, error }; - } - // TODO: Remove once: https://github.com/supabase/auth/pull/1717 is deployed - if (params.factorType === 'phone') { - delete data.totp; - } - if (params.factorType === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { - data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; - } - return { data, error: null }; - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * {@see GoTrueMFAApi#verify} - */ - async _verify(params) { - return this._acquireLock(-1, async () => { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { - body: { code: params.code, challenge_id: params.challengeId }, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - if (error) { - return { data: null, error }; - } - await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); - await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); - return { data, error }; - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * {@see GoTrueMFAApi#challenge} - */ - async _challenge(params) { - return this._acquireLock(-1, async () => { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - return await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { - body: { channel: params.channel }, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - }); - } - catch (error) { - if (isAuthError(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * {@see GoTrueMFAApi#challengeAndVerify} - */ - async _challengeAndVerify(params) { - // both _challenge and _verify independently acquire the lock, so no need - // to acquire it here - const { data: challengeData, error: challengeError } = await this._challenge({ - factorId: params.factorId, - }); - if (challengeError) { - return { data: null, error: challengeError }; - } - return await this._verify({ - factorId: params.factorId, - challengeId: challengeData.id, - code: params.code, - }); - } - /** - * {@see GoTrueMFAApi#listFactors} - */ - async _listFactors() { - // use #getUser instead of #_getUser as the former acquires a lock - const { data: { user }, error: userError, } = await this.getUser(); - if (userError) { - return { data: null, error: userError }; - } - const factors = (user === null || user === void 0 ? void 0 : user.factors) || []; - const totp = factors.filter((factor) => factor.factor_type === 'totp' && factor.status === 'verified'); - const phone = factors.filter((factor) => factor.factor_type === 'phone' && factor.status === 'verified'); - return { - data: { - all: factors, - totp, - phone, - }, - error: null, - }; - } - /** - * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} - */ - async _getAuthenticatorAssuranceLevel() { - return this._acquireLock(-1, async () => { - return await this._useSession(async (result) => { - var _a, _b; - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { - data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, - error: null, - }; - } - const payload = this._decodeJWT(session.access_token); - let currentLevel = null; - if (payload.aal) { - currentLevel = payload.aal; - } - let nextLevel = currentLevel; - const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; - if (verifiedFactors.length > 0) { - nextLevel = 'aal2'; - } - const currentAuthenticationMethods = payload.amr || []; - return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; - }); - }); - } - } - GoTrueClient.nextInstanceID = 0; - - const AuthAdminApi = GoTrueAdminApi; - - const AuthClient = GoTrueClient; - - class SupabaseAuthClient extends AuthClient { - constructor(options) { - super(options); - } - } - - 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()); - }); - }; - /** - * Supabase Client. - * - * An isomorphic Javascript client for interacting with Postgres. - */ - class SupabaseClient { - /** - * Create a new client for use in the browser. - * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. - * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. - * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. - * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. - * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. - * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. - * @param options.realtime Options passed along to realtime-js constructor. - * @param options.global.fetch A custom fetch implementation. - * @param options.global.headers Any additional headers to send with each network request. - */ - constructor(supabaseUrl, supabaseKey, options) { - var _a, _b, _c; - this.supabaseUrl = supabaseUrl; - this.supabaseKey = supabaseKey; - if (!supabaseUrl) - throw new Error('supabaseUrl is required.'); - if (!supabaseKey) - throw new Error('supabaseKey is required.'); - const _supabaseUrl = stripTrailingSlash(supabaseUrl); - this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws'); - this.authUrl = `${_supabaseUrl}/auth/v1`; - this.storageUrl = `${_supabaseUrl}/storage/v1`; - this.functionsUrl = `${_supabaseUrl}/functions/v1`; - // default storage key uses the supabase project ref as a namespace - const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`; - const DEFAULTS = { - db: DEFAULT_DB_OPTIONS, - realtime: DEFAULT_REALTIME_OPTIONS, - auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), - global: DEFAULT_GLOBAL_OPTIONS, - }; - const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS); - this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; - this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; - if (!settings.accessToken) { - this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); - } - else { - this.accessToken = settings.accessToken; - this.auth = new Proxy({}, { - get: (_, prop) => { - throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); - }, - }); - } - this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); - this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers }, settings.realtime)); - this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, { - headers: this.headers, - schema: settings.db.schema, - fetch: this.fetch, - }); - if (!settings.accessToken) { - this._listenForAuthEvents(); - } - } - /** - * Supabase Functions allows you to deploy and invoke edge functions. - */ - get functions() { - return new FunctionsClient(this.functionsUrl, { - headers: this.headers, - customFetch: this.fetch, - }); - } - /** - * Supabase Storage allows you to manage user-generated content, such as photos or videos. - */ - get storage() { - return new StorageClient(this.storageUrl, this.headers, this.fetch); - } - /** - * Perform a query on a table or a view. - * - * @param relation - The table or view name to query - */ - from(relation) { - return this.rest.from(relation); - } - // NOTE: signatures must be kept in sync with PostgrestClient.schema - /** - * Select a schema to query or perform an function (rpc) call. - * - * The schema needs to be on the list of exposed schemas inside Supabase. - * - * @param schema - The schema to query - */ - schema(schema) { - return this.rest.schema(schema); - } - // NOTE: signatures must be kept in sync with PostgrestClient.rpc - /** - * Perform a function call. - * - * @param fn - The function name to call - * @param args - The arguments to pass to the function call - * @param options - Named parameters - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * @param options.get - When set to `true`, the function will be called with - * read-only access mode. - * @param options.count - Count algorithm to use to count rows returned by the - * function. Only applicable for [set-returning - * functions](https://www.postgresql.org/docs/current/functions-srf.html). - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - rpc(fn, args = {}, options = {}) { - return this.rest.rpc(fn, args, options); - } - /** - * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. - * - * @param {string} name - The name of the Realtime channel. - * @param {Object} opts - The options to pass to the Realtime channel. - * - */ - channel(name, opts = { config: {} }) { - return this.realtime.channel(name, opts); - } - /** - * Returns all Realtime channels. - */ - getChannels() { - return this.realtime.getChannels(); - } - /** - * Unsubscribes and removes Realtime channel from Realtime client. - * - * @param {RealtimeChannel} channel - The name of the Realtime channel. - * - */ - removeChannel(channel) { - return this.realtime.removeChannel(channel); - } - /** - * Unsubscribes and removes all Realtime channels from Realtime client. - */ - removeAllChannels() { - return this.realtime.removeAllChannels(); - } - _getAccessToken() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - if (this.accessToken) { - return yield this.accessToken(); - } - const { data } = yield this.auth.getSession(); - return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : null; - }); - } - _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, storageKey, flowType, lock, debug, }, headers, fetch) { - var _a; - const authHeaders = { - Authorization: `Bearer ${this.supabaseKey}`, - apikey: `${this.supabaseKey}`, - }; - return new SupabaseAuthClient({ - url: this.authUrl, - headers: Object.assign(Object.assign({}, authHeaders), headers), - storageKey: storageKey, - autoRefreshToken, - persistSession, - detectSessionInUrl, - storage, - flowType, - lock, - debug, - fetch, - // auth checks if there is a custom authorizaiton header using this flag - // so it knows whether to return an error when getUser is called with no session - hasCustomAuthorizationHeader: (_a = 'Authorization' in this.headers) !== null && _a !== void 0 ? _a : false, - }); - } - _initRealtimeClient(options) { - return new RealtimeClient(this.realtimeUrl, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); - } - _listenForAuthEvents() { - let data = this.auth.onAuthStateChange((event, session) => { - this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); - }); - return data; - } - _handleTokenChanged(event, source, token) { - if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && - this.changedAccessToken !== token) { - // Token has changed - this.realtime.setAuth(token !== null && token !== void 0 ? token : null); - this.changedAccessToken = token; - } - else if (event === 'SIGNED_OUT') { - // Token is removed - this.realtime.setAuth(this.supabaseKey); - if (source == 'STORAGE') - this.auth.signOut(); - this.changedAccessToken = undefined; - } - } - } - - /** - * Creates a new Supabase Client. - */ - const createClient = (supabaseUrl, supabaseKey, options) => { - return new SupabaseClient(supabaseUrl, supabaseKey, options); - }; - - const __esModule = true; - - exports.AuthAdminApi = AuthAdminApi; - exports.AuthApiError = AuthApiError; - exports.AuthClient = AuthClient; - exports.AuthError = AuthError; - exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; - exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; - exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; - exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; - exports.AuthRetryableFetchError = AuthRetryableFetchError; - exports.AuthSessionMissingError = AuthSessionMissingError; - exports.AuthUnknownError = AuthUnknownError; - exports.AuthWeakPasswordError = AuthWeakPasswordError; - exports.CustomAuthError = CustomAuthError; - exports.FunctionsError = FunctionsError; - exports.FunctionsFetchError = FunctionsFetchError; - exports.FunctionsHttpError = FunctionsHttpError; - exports.FunctionsRelayError = FunctionsRelayError; - exports.GoTrueAdminApi = GoTrueAdminApi; - exports.GoTrueClient = GoTrueClient; - exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; - exports.REALTIME_CHANNEL_STATES = REALTIME_CHANNEL_STATES; - exports.RealtimeChannel = RealtimeChannel; - exports.RealtimeClient = RealtimeClient; - exports.RealtimePresence = RealtimePresence; - exports.SupabaseClient = SupabaseClient; - exports.__esModule = __esModule; - exports.createClient = createClient; - exports.isAuthApiError = isAuthApiError; - exports.isAuthError = isAuthError; - exports.isAuthRetryableFetchError = isAuthRetryableFetchError; - exports.isAuthSessionMissingError = isAuthSessionMissingError; - exports.isAuthWeakPasswordError = isAuthWeakPasswordError; - exports.lockInternals = internals; - exports.navigatorLock = navigatorLock; +sap.ui.define(['exports', 'ui5/ecosystem/demo/app/resources/index2'], (function (exports, index) { 'use strict'; + + + + exports.AuthAdminApi = index.AuthAdminApi; + exports.AuthApiError = index.AuthApiError; + exports.AuthClient = index.AuthClient; + exports.AuthError = index.AuthError; + exports.AuthImplicitGrantRedirectError = index.AuthImplicitGrantRedirectError; + exports.AuthInvalidCredentialsError = index.AuthInvalidCredentialsError; + exports.AuthInvalidTokenResponseError = index.AuthInvalidTokenResponseError; + exports.AuthPKCEGrantCodeExchangeError = index.AuthPKCEGrantCodeExchangeError; + exports.AuthRetryableFetchError = index.AuthRetryableFetchError; + exports.AuthSessionMissingError = index.AuthSessionMissingError; + exports.AuthUnknownError = index.AuthUnknownError; + exports.AuthWeakPasswordError = index.AuthWeakPasswordError; + exports.CustomAuthError = index.CustomAuthError; + Object.defineProperty(exports, "FunctionRegion", { + enumerable: true, + get: function () { return index.FunctionRegion; } + }); + exports.FunctionsError = index.FunctionsError; + exports.FunctionsFetchError = index.FunctionsFetchError; + exports.FunctionsHttpError = index.FunctionsHttpError; + exports.FunctionsRelayError = index.FunctionsRelayError; + exports.GoTrueAdminApi = index.GoTrueAdminApi; + exports.GoTrueClient = index.GoTrueClient; + exports.NavigatorLockAcquireTimeoutError = index.NavigatorLockAcquireTimeoutError; + exports.REALTIME_CHANNEL_STATES = index.REALTIME_CHANNEL_STATES; + Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { + enumerable: true, + get: function () { return index.REALTIME_LISTEN_TYPES; } + }); + Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", { + enumerable: true, + get: function () { return index.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } + }); + Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", { + enumerable: true, + get: function () { return index.REALTIME_PRESENCE_LISTEN_EVENTS; } + }); + Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", { + enumerable: true, + get: function () { return index.REALTIME_SUBSCRIBE_STATES; } + }); + exports.RealtimeChannel = index.RealtimeChannel; + exports.RealtimeClient = index.RealtimeClient; + exports.RealtimePresence = index.RealtimePresence; + exports.SupabaseClient = index.SupabaseClient; + exports.__esModule = index.__esModule; + exports.createClient = index.createClient; + exports.isAuthApiError = index.isAuthApiError; + exports.isAuthError = index.isAuthError; + exports.isAuthRetryableFetchError = index.isAuthRetryableFetchError; + exports.isAuthSessionMissingError = index.isAuthSessionMissingError; + exports.isAuthWeakPasswordError = index.isAuthWeakPasswordError; + exports.lockInternals = index.internals; + exports.navigatorLock = index.navigatorLock; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/a230bdfe/index2.js b/packages/ui5-tooling-modules/test/__snap__/a230bdfe/index2.js new file mode 100644 index 000000000..ce8f60db1 --- /dev/null +++ b/packages/ui5-tooling-modules/test/__snap__/a230bdfe/index2.js @@ -0,0 +1,9188 @@ +sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict'; + + const resolveFetch$3 = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); + }; + + class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; + } + } + class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); + } + } + class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } + } + class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } + } + // Define the enum for the 'region' property + exports.FunctionRegion = void 0; + (function (FunctionRegion) { + FunctionRegion["Any"] = "any"; + FunctionRegion["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion["ApSouth1"] = "ap-south-1"; + FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion["CaCentral1"] = "ca-central-1"; + FunctionRegion["EuCentral1"] = "eu-central-1"; + FunctionRegion["EuWest1"] = "eu-west-1"; + FunctionRegion["EuWest2"] = "eu-west-2"; + FunctionRegion["EuWest3"] = "eu-west-3"; + FunctionRegion["SaEast1"] = "sa-east-1"; + FunctionRegion["UsEast1"] = "us-east-1"; + FunctionRegion["UsWest1"] = "us-west-1"; + FunctionRegion["UsWest2"] = "us-west-2"; + })(exports.FunctionRegion || (exports.FunctionRegion = {})); + + var __awaiter$7 = (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()); + }); + }; + class FunctionsClient { + constructor(url, { headers = {}, customFetch, region = exports.FunctionRegion.Any, } = {}) { + this.url = url; + this.headers = headers; + this.region = region; + this.fetch = resolveFetch$3(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName, options = {}) { + var _a; + return __awaiter$7(this, void 0, void 0, function* () { + try { + const { headers, method, body: functionArgs } = options; + let _headers = {}; + let { region } = options; + if (!region) { + region = this.region; + } + if (region && region !== 'any') { + _headers['x-region'] = region; + } + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + const response = yield this.fetch(`${this.url}/${functionName}`, { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + }).catch((fetchError) => { + throw new FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new FunctionsRelayError(response); + } + if (!response.ok) { + throw new FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream') { + data = yield response.blob(); + } + else if (responseType === 'text/event-stream') { + data = response; + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null }; + } + catch (error) { + return { data: null, error }; + } + }); + } + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + 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 cjs = {}; + + var PostgrestClient$2 = {}; + + var PostgrestQueryBuilder$1 = {}; + + var PostgrestFilterBuilder$1 = {}; + + var PostgrestTransformBuilder$1 = {}; + + var PostgrestBuilder$1 = {}; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // ref: https://github.com/tc39/proposal-global + var getGlobal = function() { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + 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'); + }; + + var globalObject = getGlobal(); + + const fetch$1 = globalObject.fetch; + + var nodeFetch = globalObject.fetch.bind(globalObject); + + const Headers$1 = globalObject.Headers; + const Request = globalObject.Request; + const Response$1 = globalObject.Response; + + var browser = /*#__PURE__*/Object.freeze({ + __proto__: null, + Headers: Headers$1, + Request: Request, + Response: Response$1, + default: nodeFetch, + fetch: fetch$1 + }); + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(browser); + + var PostgrestError$1 = {}; + + Object.defineProperty(PostgrestError$1, "__esModule", { value: true }); + class PostgrestError extends Error { + constructor(context) { + super(context.message); + this.name = 'PostgrestError'; + this.details = context.details; + this.hint = context.hint; + this.code = context.code; + } + } + PostgrestError$1.default = PostgrestError; + + var __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(PostgrestBuilder$1, "__esModule", { value: true }); + // @ts-ignore + const node_fetch_1 = __importDefault$5(require$$0); + const PostgrestError_1 = __importDefault$5(PostgrestError$1); + class PostgrestBuilder { + constructor(builder) { + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = builder.headers; + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = builder.shouldThrowOnError; + this.signal = builder.signal; + this.isMaybeSingle = builder.isMaybeSingle; + if (builder.fetch) { + this.fetch = builder.fetch; + } + else if (typeof fetch === 'undefined') { + this.fetch = node_fetch_1.default; + } + else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + then(onfulfilled, onrejected) { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) ; + else if (['GET', 'HEAD'].includes(this.method)) { + this.headers['Accept-Profile'] = this.schema; + } + else { + this.headers['Content-Profile'] = this.schema; + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers['Content-Type'] = 'application/json'; + } + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + var _a, _b, _c; + let error = null; + let data = null; + let count = null; + let status = res.status; + let statusText = res.statusText; + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text(); + if (body === '') ; + else if (this.headers['Accept'] === 'text/csv') { + data = body; + } + else if (this.headers['Accept'] && + this.headers['Accept'].includes('application/vnd.pgrst.plan+text')) { + data = body; + } + else { + data = JSON.parse(body); + } + } + const countHeader = (_a = this.headers['Prefer']) === null || _a === void 0 ? void 0 : _a.match(/count=(exact|planned|estimated)/); + const contentRange = (_b = res.headers.get('content-range')) === null || _b === void 0 ? void 0 : _b.split('/'); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + }; + data = null; + count = null; + status = 406; + statusText = 'Not Acceptable'; + } + else if (data.length === 1) { + data = data[0]; + } + else { + data = null; + } + } + } + else { + const body = await res.text(); + try { + error = JSON.parse(body); + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = []; + error = null; + status = 200; + statusText = 'OK'; + } + } + catch (_d) { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204; + statusText = 'No Content'; + } + else { + error = { + message: body, + }; + } + } + if (error && this.isMaybeSingle && ((_c = error === null || error === void 0 ? void 0 : error.details) === null || _c === void 0 ? void 0 : _c.includes('0 rows'))) { + error = null; + status = 200; + statusText = 'OK'; + } + if (error && this.shouldThrowOnError) { + throw new PostgrestError_1.default(error); + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText, + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c; + return ({ + error: { + message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, + hint: '', + code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, + }, + data: null, + count: null, + status: 0, + statusText: '', + }); + }); + } + return res.then(onfulfilled, onrejected); + } + } + PostgrestBuilder$1.default = PostgrestBuilder; + + var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(PostgrestTransformBuilder$1, "__esModule", { value: true }); + const PostgrestBuilder_1$1 = __importDefault$4(PostgrestBuilder$1); + class PostgrestTransformBuilder extends PostgrestBuilder_1$1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (this.headers['Prefer']) { + this.headers['Prefer'] += ','; + } + this.headers['Prefer'] += 'return=representation'; + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.order` : 'order'; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; + } + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { + const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; + const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers['Accept'] = 'application/vnd.pgrst.object+json'; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers['Accept'] = 'application/json'; + } + else { + this.headers['Accept'] = 'application/vnd.pgrst.object+json'; + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers['Accept'] = 'text/csv'; + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers['Accept'] = 'application/geo+json'; + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { + var _a; + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|'); + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = (_a = this.headers['Accept']) !== null && _a !== void 0 ? _a : 'application/json'; + this.headers['Accept'] = `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`; + if (format === 'json') + return this; + else + return this; + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + var _a; + if (((_a = this.headers['Prefer']) !== null && _a !== void 0 ? _a : '').trim().length > 0) { + this.headers['Prefer'] += ',tx=rollback'; + } + else { + this.headers['Prefer'] = 'tx=rollback'; + } + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + */ + returns() { + return this; + } + } + PostgrestTransformBuilder$1.default = PostgrestTransformBuilder; + + var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(PostgrestFilterBuilder$1, "__esModule", { value: true }); + const PostgrestTransformBuilder_1$1 = __importDefault$3(PostgrestTransformBuilder$1); + class PostgrestFilterBuilder extends PostgrestTransformBuilder_1$1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; + } + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = Array.from(new Set(values)) + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && new RegExp('[,()]').test(s)) + return `"${s}"`; + else + return `${s}`; + }) + .join(','); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`); + } + else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ''; + if (type === 'plain') { + typePart = 'pl'; + } + else if (type === 'phrase') { + typePart = 'ph'; + } + else if (type === 'websearch') { + typePart = 'w'; + } + const configPart = config === undefined ? '' : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.or` : 'or'; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } + } + PostgrestFilterBuilder$1.default = PostgrestFilterBuilder; + + var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(PostgrestQueryBuilder$1, "__esModule", { value: true }); + const PostgrestFilterBuilder_1$2 = __importDefault$2(PostgrestFilterBuilder$1); + class PostgrestQueryBuilder { + constructor(url, { headers = {}, schema, fetch, }) { + this.url = url; + this.headers = headers; + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, { head = false, count, } = {}) { + const method = head ? 'HEAD' : 'GET'; + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (count) { + this.headers['Prefer'] = `count=${count}`; + } + return new PostgrestFilterBuilder_1$2.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert(values, { count, defaultToNull = true, } = {}) { + const method = 'POST'; + const prefersHeaders = []; + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (!defaultToNull) { + prefersHeaders.push('missing=default'); + } + this.headers['Prefer'] = prefersHeaders.join(','); + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1$2.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { + const method = 'POST'; + const prefersHeaders = [`resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`]; + if (onConflict !== undefined) + this.url.searchParams.set('on_conflict', onConflict); + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (!defaultToNull) { + prefersHeaders.push('missing=default'); + } + this.headers['Prefer'] = prefersHeaders.join(','); + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1$2.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count, } = {}) { + const method = 'PATCH'; + const prefersHeaders = []; + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + this.headers['Prefer'] = prefersHeaders.join(','); + return new PostgrestFilterBuilder_1$2.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, } = {}) { + const method = 'DELETE'; + const prefersHeaders = []; + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (this.headers['Prefer']) { + prefersHeaders.unshift(this.headers['Prefer']); + } + this.headers['Prefer'] = prefersHeaders.join(','); + return new PostgrestFilterBuilder_1$2.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + }); + } + } + PostgrestQueryBuilder$1.default = PostgrestQueryBuilder; + + var constants = {}; + + var version$4 = {}; + + Object.defineProperty(version$4, "__esModule", { value: true }); + version$4.version = void 0; + version$4.version = '0.0.0-automated'; + + Object.defineProperty(constants, "__esModule", { value: true }); + constants.DEFAULT_HEADERS = void 0; + const version_1 = version$4; + constants.DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version_1.version}` }; + + var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(PostgrestClient$2, "__esModule", { value: true }); + const PostgrestQueryBuilder_1$1 = __importDefault$1(PostgrestQueryBuilder$1); + const PostgrestFilterBuilder_1$1 = __importDefault$1(PostgrestFilterBuilder$1); + const constants_1 = constants; + /** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ + let PostgrestClient$1 = class PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url, { headers = {}, schema, fetch, } = {}) { + this.url = url; + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.schemaName = schema; + this.fetch = fetch; + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1$1.default(url, { + headers: Object.assign({}, this.headers), + schema: this.schemaName, + fetch: this.fetch, + }); + } + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return new PostgrestClient(this.url, { + headers: this.headers, + schema, + fetch: this.fetch, + }); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, { head = false, get = false, count, } = {}) { + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head || get) { + method = head ? 'HEAD' : 'GET'; + Object.entries(args) + // params with undefined value needs to be filtered out, otherwise it'll + // show up as `?param=undefined` + .filter(([_, value]) => value !== undefined) + // array values need special syntax + .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) + .forEach(([name, value]) => { + url.searchParams.append(name, value); + }); + } + else { + method = 'POST'; + body = args; + } + const headers = Object.assign({}, this.headers); + if (count) { + headers['Prefer'] = `count=${count}`; + } + return new PostgrestFilterBuilder_1$1.default({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: this.fetch, + allowEmpty: false, + }); + } + }; + PostgrestClient$2.default = PostgrestClient$1; + + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(cjs, "__esModule", { value: true }); + cjs.PostgrestBuilder = cjs.PostgrestTransformBuilder = cjs.PostgrestFilterBuilder = cjs.PostgrestQueryBuilder = PostgrestClient = cjs.PostgrestClient = void 0; + // Always update wrapper.mjs when updating this file. + const PostgrestClient_1 = __importDefault(PostgrestClient$2); + var PostgrestClient = cjs.PostgrestClient = PostgrestClient_1.default; + const PostgrestQueryBuilder_1 = __importDefault(PostgrestQueryBuilder$1); + cjs.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; + const PostgrestFilterBuilder_1 = __importDefault(PostgrestFilterBuilder$1); + cjs.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; + const PostgrestTransformBuilder_1 = __importDefault(PostgrestTransformBuilder$1); + cjs.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; + const PostgrestBuilder_1 = __importDefault(PostgrestBuilder$1); + cjs.PostgrestBuilder = PostgrestBuilder_1.default; + cjs.default = { + PostgrestClient: PostgrestClient_1.default, + PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, + PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, + PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, + PostgrestBuilder: PostgrestBuilder_1.default, + }; + + const version$3 = '2.10.2'; + + const DEFAULT_HEADERS$3 = { 'X-Client-Info': `realtime-js/${version$3}` }; + const VSN = '1.0.0'; + const DEFAULT_TIMEOUT = 10000; + const WS_CLOSE_NORMAL = 1000; + var SOCKET_STATES; + (function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; + })(SOCKET_STATES || (SOCKET_STATES = {})); + var CHANNEL_STATES; + (function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; + })(CHANNEL_STATES || (CHANNEL_STATES = {})); + var CHANNEL_EVENTS; + (function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; + })(CHANNEL_EVENTS || (CHANNEL_EVENTS = {})); + var TRANSPORTS; + (function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; + })(TRANSPORTS || (TRANSPORTS = {})); + var CONNECTION_STATE; + (function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; + })(CONNECTION_STATE || (CONNECTION_STATE = {})); + + // This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe + // License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md + class Serializer { + constructor() { + this.HEADER_LENGTH = 1; + } + decode(rawPayload, callback) { + if (rawPayload.constructor === ArrayBuffer) { + return callback(this._binaryDecode(rawPayload)); + } + if (typeof rawPayload === 'string') { + return callback(JSON.parse(rawPayload)); + } + return callback({}); + } + _binaryDecode(buffer) { + const view = new DataView(buffer); + const decoder = new TextDecoder(); + return this._decodeBroadcast(buffer, view, decoder); + } + _decodeBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const eventSize = view.getUint8(2); + let offset = this.HEADER_LENGTH + 2; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const event = decoder.decode(buffer.slice(offset, offset + eventSize)); + offset = offset + eventSize; + const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); + return { ref: null, topic: topic, event: event, payload: data }; + } + } + + /** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ + class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } + } + + /** + * Helpers to convert the change Payload into native JS types. + */ + // Adapted from epgsql (src/epgsql_binary.erl), this module licensed under + // 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE + var PostgresTypes; + (function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; + })(PostgresTypes || (PostgresTypes = {})); + /** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ + const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes); + return acc; + }, {}); + }; + /** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ + const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return convertCell(colType, value); + } + return noop$1(value); + }; + /** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ + const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return toArray(value, dataType); + } + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return toBoolean(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return toNumber(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return toJson(value); + case PostgresTypes.timestamp: + return toTimestampString(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop$1(value); + default: + // Return the value for remaining types + return noop$1(value); + } + }; + const noop$1 = (value) => { + return value; + }; + const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } + }; + const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; + }; + const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; + }; + /** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ + const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => convertCell(type, val)); + } + return value; + }; + /** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ + const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; + }; + const httpEndpointURL = (socketUrl) => { + let url = socketUrl; + url = url.replace(/^ws/i, 'http'); + url = url.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i, ''); + return url.replace(/\/+$/, ''); + }; + + class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived('timeout')) { + return; + } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; + } + _matchReceive({ status, response, }) { + this.recHooks + .filter((h) => h.status === status) + .forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } + } + + /* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md + */ + exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; + (function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; + })(exports.REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = {})); + class RealtimePresence { + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; + } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } + } + + exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; + (function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; + })(exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); + exports.REALTIME_LISTEN_TYPES = void 0; + (function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + /** + * listen to Postgres changes. + */ + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; + })(exports.REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = {})); + exports.REALTIME_SUBSCRIBE_STATES = void 0; + (function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; + })(exports.REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = {})); + const REALTIME_CHANNEL_STATES = CHANNEL_STATES; + /** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ + class RealtimeChannel { + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ''); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '' }, + private: false, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new Timer(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence(this); + this.broadcastEndpointURL = + httpEndpointURL(this.socket.endPoint) + '/api/broadcast'; + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.joinedOnce) { + throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance`; + } + else { + const { config: { broadcast, presence, private: isPrivate }, } = this.params; + this._onError((e) => callback && callback('CHANNEL_ERROR', e)); + this._onClose(() => callback && callback('CLOSED')); + const accessTokenPayload = {}; + const config = { + broadcast, + presence, + postgres_changes: (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : [], + private: isPrivate, + }; + if (this.socket.accessToken) { + accessTokenPayload.access_token = this.socket.accessToken; + } + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', ({ postgres_changes: serverPostgresFilters, }) => { + var _a; + this.socket.accessToken && + this.socket.setAuth(this.socket.accessToken); + if (serverPostgresFilters === undefined) { + callback && callback('SUBSCRIBED'); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = serverPostgresFilters && serverPostgresFilters[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + serverPostgresFilter.schema === schema && + serverPostgresFilter.table === table && + serverPostgresFilter.filter === filter) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + callback && + callback('CHANNEL_ERROR', new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback('SUBSCRIBED'); + return; + } + }) + .receive('error', (error) => { + callback && + callback('CHANNEL_ERROR', new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback && callback('TIMED_OUT'); + return; + }); + } + return this; + } + presenceState() { + return this.presence.state; + } + async track(payload, opts = {}) { + return await this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); + } + async untrack(opts = {}) { + return await this.send({ + type: 'presence', + event: 'untrack', + }, opts); + } + on(type, filter, callback) { + return this._on(type, filter, callback); + } + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a, _b; + if (!this._canPush() && args.type === 'broadcast') { + const { event, payload: endpoint_payload } = args; + const options = { + method: 'POST', + headers: { + Authorization: this.socket.accessToken + ? `Bearer ${this.socket.accessToken}` + : '', + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { topic: this.subTopic, event, payload: endpoint_payload }, + ], + }), + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? 'ok' : 'error'; + } + catch (error) { + if (error.name === 'AbortError') { + return 'timed out'; + } + else { + return 'error'; + } + } + } + else { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('error', () => resolve('error')); + push.receive('timeout', () => resolve('timed out')); + }); + } + } + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.rejoinTimer.reset(); + // Destroy joinPush to avoid connection timeouts during unscription phase + this.joinPush.destroy(); + return new Promise((resolve) => { + const leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }); + } + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new Push(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + } + return pushEvent; + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; + } + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return (((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || + ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower); + }).map((bind) => bind.callback(handledPayload, ref)); + } + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === + ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return (bindEvent === '*' || + bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase())); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } + else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = convertChangeData(payload.columns, payload.old_record); + } + return records; + } + } + + const noop = () => { }; + const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined'; + class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers The optional headers to pass when connecting. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + */ + constructor(endPoint, options) { + var _a; + this.accessToken = null; + this.apiKey = null; + this.channels = []; + this.endPoint = ''; + this.httpEndpoint = ''; + this.headers = DEFAULT_HEADERS$3; + this.params = {}; + this.timeout = DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = 30000; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.ref = 0; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new Serializer(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + /** + * Use either custom fetch, if provided, or default fetch to make HTTP requests + * + * @internal + */ + this._resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); + }; + this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`; + this.httpEndpoint = httpEndpointURL(endPoint); + if (options === null || options === void 0 ? void 0 : options.transport) { + this.transport = options.transport; + } + else { + this.transport = null; + } + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.headers) + this.headers = Object.assign(Object.assign({}, this.headers), options.headers); + if (options === null || options === void 0 ? void 0 : options.timeout) + this.timeout = options.timeout; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if (options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) + this.heartbeatIntervalMs = options.heartbeatIntervalMs; + const accessToken = (_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey; + if (accessToken) { + this.accessToken = accessToken; + this.apiKey = accessToken; + } + this.reconnectAfterMs = (options === null || options === void 0 ? void 0 : options.reconnectAfterMs) + ? options.reconnectAfterMs + : (tries) => { + return [1000, 2000, 5000, 10000][tries - 1] || 10000; + }; + this.encode = (options === null || options === void 0 ? void 0 : options.encode) + ? options.encode + : (payload, callback) => { + return callback(JSON.stringify(payload)); + }; + this.decode = (options === null || options === void 0 ? void 0 : options.decode) + ? options.decode + : this.serializer.decode.bind(this.serializer); + this.reconnectTimer = new Timer(async () => { + this.disconnect(); + this.connect(); + }, this.reconnectAfterMs); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + if (this.conn) { + return; + } + if (this.transport) { + this.conn = new this.transport(this._endPointURL(), undefined, { + headers: this.headers, + }); + return; + } + if (NATIVE_WEBSOCKET_AVAILABLE) { + this.conn = new WebSocket(this._endPointURL()); + this.setupConnection(); + return; + } + this.conn = new WSWebSocketDummy(this._endPointURL(), undefined, { + close: () => { + this.conn = null; + }, + }); + new Promise(function (resolve, reject) { require(['ui5/ecosystem/demo/app/resources/wrapper'], resolve, reject); }).then(({ default: WS }) => { + this.conn = new WS(this._endPointURL(), undefined, { + headers: this.headers, + }); + this.setupConnection(); + }); + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.conn) { + this.conn.onclose = function () { }; // noop + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + this.conn = null; + // remove open handles + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.reconnectTimer.reset(); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + } + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.disconnect(); + return values_1; + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case SOCKET_STATES.connecting: + return CONNECTION_STATE.Connecting; + case SOCKET_STATES.open: + return CONNECTION_STATE.Open; + case SOCKET_STATES.closing: + return CONNECTION_STATE.Closing; + default: + return CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === CONNECTION_STATE.Open; + } + channel(topic, params = { config: {} }) { + const chan = new RealtimeChannel(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } + else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * @param token A JWT string. + */ + setAuth(token) { + this.accessToken = token; + this.channels.forEach((channel) => { + token && channel.updateJoinPayload({ access_token: token }); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(CHANNEL_EVENTS.access_token, { access_token: token }); + } + }); + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c._joinRef() !== channel._joinRef()); + } + /** + * Sets up connection handlers. + * + * @internal + */ + setupConnection() { + if (this.conn) { + this.conn.binaryType = 'arraybuffer'; + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + } + /** + * Returns the URL of the websocket. + * + * @internal + */ + _endPointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: VSN })); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + let { topic, event, payload, ref } = msg; + if ((ref && ref === this.pendingHeartbeatRef) || + event === (payload === null || payload === void 0 ? void 0 : payload.type)) { + this.pendingHeartbeatRef = null; + } + this.log('receive', `${payload.status || ''} ${topic} ${event} ${(ref && '(' + ref + ')') || ''}`, payload); + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this.stateChangeCallbacks.message.forEach((callback) => callback(msg)); + }); + } + /** @internal */ + _onConnOpen() { + this.log('transport', `connected to ${this._endPointURL()}`); + this._flushSendBuffer(); + this.reconnectTimer.reset(); + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this._sendHeartbeat(), this.heartbeatIntervalMs); + this.stateChangeCallbacks.open.forEach((callback) => callback()); + } + /** @internal */ + _onConnClose(event) { + this.log('transport', 'close', event); + this._triggerChanError(); + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.reconnectTimer.scheduleTimeout(); + this.stateChangeCallbacks.close.forEach((callback) => callback(event)); + } + /** @internal */ + _onConnError(error) { + this.log('transport', error.message); + this._triggerChanError(); + this.stateChangeCallbacks.error.forEach((callback) => callback(error)); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + /** @internal */ + _flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** @internal */ + _sendHeartbeat() { + var _a; + if (!this.isConnected()) { + return; + } + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(WS_CLOSE_NORMAL, 'hearbeat timeout'); + return; + } + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + this.setAuth(this.accessToken); + } + } + class WSWebSocketDummy { + constructor(address, _protocols, options) { + this.binaryType = 'arraybuffer'; + this.onclose = () => { }; + this.onerror = () => { }; + this.onmessage = () => { }; + this.onopen = () => { }; + this.readyState = SOCKET_STATES.connecting; + this.send = () => { }; + this.url = null; + this.url = address; + this.close = options.close; + } + } + + 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; + } + + function toByteArray(b64) { + if (!inited) { + init(); + } + 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"); + } + + // 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 = + 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 = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + var _kMaxLength = 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; + } + } + 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 (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + 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); + } + + 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); + } + return that; + } + + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that; + } + + obj.copy(that, 0, 0, len); + return that; + } + + 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 (obj.type === "Buffer" && isArray(obj.data)) { + return fromArrayLike(that, obj.data); + } + } + + 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; + } + + function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length); + } + Buffer.isBuffer = isBuffer; + 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(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); + + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + + // 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; + } + + 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"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + 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"); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + 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"); + } + 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 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); + }; + + 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; + }; + + 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 ""; + }; + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); + } + + 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; + } + 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); + } + + // 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() + } + + // 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; + } + + 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); + } + 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 ret; + } + + 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; + 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 < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + 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; + }; + + /* + * 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 val; + }; + + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + 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(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)); + } + + let Blob$1 = class Blob {}; + + var _polyfillNode_buffer = /*#__PURE__*/Object.freeze({ + __proto__: null, + Blob: Blob$1, + Buffer: Buffer, + INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, + SlowBuffer: SlowBuffer, + isBuffer: isBuffer, + kMaxLength: _kMaxLength + }); + + class StorageError extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = 'StorageError'; + } + } + function isStorageError(error) { + return typeof error === 'object' && error !== null && '__isStorageError' in error; + } + class StorageApiError extends StorageError { + constructor(message, status) { + super(message); + this.name = 'StorageApiError'; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } + } + class StorageUnknownError extends StorageError { + constructor(message, originalError) { + super(message); + this.name = 'StorageUnknownError'; + this.originalError = originalError; + } + } + + var __awaiter$6 = (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()); + }); + }; + const resolveFetch$2 = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); + }; + const resolveResponse = () => __awaiter$6(void 0, void 0, void 0, function* () { + if (typeof Response === 'undefined') { + // @ts-ignore + return (yield Promise.resolve().then(function () { return browser; })).Response; + } + return Response; + }); + const recursiveToCamel = (item) => { + if (Array.isArray(item)) { + return item.map((el) => recursiveToCamel(el)); + } + else if (typeof item === 'function' || item !== Object(item)) { + return item; + } + const result = {}; + Object.entries(item).forEach(([key, value]) => { + const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')); + result[newKey] = recursiveToCamel(value); + }); + return result; + }; + + var __awaiter$5 = (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()); + }); + }; + const _getErrorMessage$1 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); + const handleError$1 = (error, reject, options) => __awaiter$5(void 0, void 0, void 0, function* () { + const Res = yield resolveResponse(); + if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + error + .json() + .then((err) => { + reject(new StorageApiError(_getErrorMessage$1(err), error.status || 500)); + }) + .catch((err) => { + reject(new StorageUnknownError(_getErrorMessage$1(err), err)); + }); + } + else { + reject(new StorageUnknownError(_getErrorMessage$1(error), error)); + } + }); + const _getRequestParams$1 = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + if (body) { + params.body = JSON.stringify(body); + } + return Object.assign(Object.assign({}, params), parameters); + }; + function _handleRequest$1(fetcher, method, url, options, parameters, body) { + return __awaiter$5(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams$1(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError$1(error, reject, options)); + }); + }); + } + function get(fetcher, url, options, parameters) { + return __awaiter$5(this, void 0, void 0, function* () { + return _handleRequest$1(fetcher, 'GET', url, options, parameters); + }); + } + function post(fetcher, url, body, options, parameters) { + return __awaiter$5(this, void 0, void 0, function* () { + return _handleRequest$1(fetcher, 'POST', url, options, parameters, body); + }); + } + function put(fetcher, url, body, options, parameters) { + return __awaiter$5(this, void 0, void 0, function* () { + return _handleRequest$1(fetcher, 'PUT', url, options, parameters, body); + }); + } + function head(fetcher, url, options, parameters) { + return __awaiter$5(this, void 0, void 0, function* () { + return _handleRequest$1(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); + }); + } + function remove(fetcher, url, body, options, parameters) { + return __awaiter$5(this, void 0, void 0, function* () { + return _handleRequest$1(fetcher, 'DELETE', url, options, parameters, body); + }); + } + + var __awaiter$4 = (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()); + }); + }; + const DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: 'name', + order: 'asc', + }, + }; + const DEFAULT_FILE_OPTIONS = { + cacheControl: '3600', + contentType: 'text/plain;charset=UTF-8', + upsert: false, + }; + class StorageFileApi { + constructor(url, headers = {}, bucketId, fetch) { + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = resolveFetch$2(fetch); + } + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); + const metadata = options.metadata; + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + if (metadata) { + body.append('metadata', this.encodeMetadata(metadata)); + } + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + if (metadata) { + body.append('metadata', this.encodeMetadata(metadata)); + } + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + if (metadata) { + headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata)); + } + } + if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { + headers = Object.assign(Object.assign({}, headers), fileOptions.headers); + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body: body, headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); + const data = yield res.json(); + if (res.ok) { + return { + data: { path: cleanPath, id: data.Id, fullPath: data.Key }, + error: null, + }; + } + else { + const error = data; + return { data: null, error }; + } + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path, fileBody, fileOptions) { + return __awaiter$4(this, void 0, void 0, function* () { + return this.uploadOrUpdate('POST', path, fileBody, fileOptions); + }); + } + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return __awaiter$4(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set('token', token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const res = yield this.fetch(url.toString(), { + method: 'PUT', + body: body, + headers, + }); + const data = yield res.json(); + if (res.ok) { + return { + data: { path: cleanPath, fullPath: data.Key }, + error: null, + }; + } + else { + const error = data; + return { data: null, error }; + } + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for 2 hours. + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param options.upsert If set to true, allows the file to be overwritten if it already exists. + */ + createSignedUploadUrl(path, options) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const headers = Object.assign({}, this.headers); + if (options === null || options === void 0 ? void 0 : options.upsert) { + headers['x-upsert'] = 'true'; + } + const data = yield post(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get('token'); + if (!token) { + throw new StorageError('No token returned by API'); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path, fileBody, fileOptions) { + return __awaiter$4(this, void 0, void 0, function* () { + return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); + }); + } + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + * @param options The destination options. + */ + move(fromPath, toPath, options) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/object/move`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + * @param options The destination options. + */ + copy(fromPath, toPath, options) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/object/copy`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, + }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + createSignedUrl(path, expiresIn, options) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield post(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths, expiresIn, options) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + return { + data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL + ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) + : null }))), + error: null, + }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path, options) { + return __awaiter$4(this, void 0, void 0, function* () { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ''; + try { + const _path = this._getFinalPath(path); + const res = yield get(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true, + }); + const data = yield res.blob(); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing file. + * @param path + */ + info(path) { + return __awaiter$4(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + const data = yield get(this.fetch, `${this.url}/object/info/${_path}`, { + headers: this.headers, + }); + return { data: recursiveToCamel(data), error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Checks the existence of a file. + * @param path + */ + exists(path) { + return __awaiter$4(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + yield head(this.fetch, `${this.url}/object/${_path}`, { + headers: this.headers, + }); + return { data: true, error: null }; + } + catch (error) { + if (isStorageError(error) && error instanceof StorageUnknownError) { + const originalError = error.originalError; + if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { + return { data: false, error }; + } + } + throw error; + } + }); + } + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `download=${options.download === true ? '' : options.download}` + : ''; + if (downloadQueryParam !== '') { + _queryString.push(downloadQueryParam); + } + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== '') { + _queryString.push(transformationQuery); + } + let queryString = _queryString.join('&'); + if (queryString !== '') { + queryString = `?${queryString}`; + } + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, + }; + } + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + const data = yield remove(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files within a bucket. + * @param path The folder path. + */ + list(path, options, parameters) { + return __awaiter$4(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); + const data = yield post(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + encodeMetadata(metadata) { + return JSON.stringify(metadata); + } + toBase64(data) { + if (typeof Buffer !== 'undefined') { + return Buffer.from(data).toString('base64'); + } + return btoa(data); + } + _getFinalPath(path) { + return `${this.bucketId}/${path}`; + } + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); + } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join('&'); + } + } + + // generated by genversion + const version$2 = '2.7.0'; + + const DEFAULT_HEADERS$2 = { 'X-Client-Info': `storage-js/${version$2}` }; + + var __awaiter$3 = (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()); + }); + }; + class StorageBucketApi { + constructor(url, headers = {}, fetch) { + this.url = url; + this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS$2), headers); + this.fetch = resolveFetch$2(fetch); + } + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets() { + return __awaiter$3(this, void 0, void 0, function* () { + try { + const data = yield get(this.fetch, `${this.url}/bucket`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id) { + return __awaiter$3(this, void 0, void 0, function* () { + try { + const data = yield get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + */ + createBucket(id, options = { + public: false, + }) { + return __awaiter$3(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/bucket`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id, options) { + return __awaiter$3(this, void 0, void 0, function* () { + try { + const data = yield put(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id) { + return __awaiter$3(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id) { + return __awaiter$3(this, void 0, void 0, function* () { + try { + const data = yield remove(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + } + + class StorageClient extends StorageBucketApi { + constructor(url, headers = {}, fetch) { + super(url, headers, fetch); + } + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id) { + return new StorageFileApi(this.url, this.headers, id, this.fetch); + } + } + + const version$1 = '2.45.3'; + + let JS_ENV = ''; + // @ts-ignore + if (typeof Deno !== 'undefined') { + JS_ENV = 'deno'; + } + else if (typeof document !== 'undefined') { + JS_ENV = 'web'; + } + else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + JS_ENV = 'react-native'; + } + else { + JS_ENV = 'node'; + } + const DEFAULT_HEADERS$1 = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version$1}` }; + const DEFAULT_GLOBAL_OPTIONS = { + headers: DEFAULT_HEADERS$1, + }; + const DEFAULT_DB_OPTIONS = { + schema: 'public', + }; + const DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', + }; + const DEFAULT_REALTIME_OPTIONS = {}; + + var __awaiter$2 = (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()); + }); + }; + const resolveFetch$1 = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = nodeFetch; + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); + }; + const resolveHeadersConstructor = () => { + if (typeof Headers === 'undefined') { + return Headers$1; + } + return Headers; + }; + const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = resolveFetch$1(customFetch); + const HeadersConstructor = resolveHeadersConstructor(); + return (input, init) => __awaiter$2(void 0, void 0, void 0, function* () { + var _a; + const accessToken = (_a = (yield getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }); + }; + + 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()); + }); + }; + function stripTrailingSlash(url) { + return url.replace(/\/$/, ''); + } + function applySettingDefaults(options, defaults) { + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + global: Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), + accessToken: () => __awaiter$1(this, void 0, void 0, function* () { return ''; }), + }; + if (options.accessToken) { + result.accessToken = options.accessToken; + } + else { + // hack around Required<> + delete result.accessToken; + } + return result; + } + + const version = '2.65.0'; + + const GOTRUE_URL = 'http://localhost:9999'; + const STORAGE_KEY = 'supabase.auth.token'; + const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` }; + const EXPIRY_MARGIN = 10; // in seconds + const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; + const API_VERSIONS = { + '2024-01-01': { + timestamp: Date.parse('2024-01-01T00:00:00.0Z'), + name: '2024-01-01', + }, + }; + + function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; + } + function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); + } + const isBrowser = () => typeof document !== 'undefined'; + const localStorageWriteTests = { + tested: false, + writable: false, + }; + /** + * Checks whether localStorage is supported on this browser. + */ + const supportsLocalStorage = () => { + if (!isBrowser()) { + return false; + } + try { + if (typeof globalThis.localStorage !== 'object') { + return false; + } + } + catch (e) { + // DOM exception when accessing `localStorage` + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; + }; + /** + * Extracts parameters encoded in the URL both in the query and fragment. + */ + function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } + } + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; + } + const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => Promise.resolve().then(function () { return browser; }).then(({ default: fetch }) => fetch(...args)); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); + }; + const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); + }; + // Storage helpers + const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); + }; + const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } + catch (_a) { + return value; + } + }; + const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); + }; + function decodeBase64URL(value) { + const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + let base64 = ''; + let chr1, chr2, chr3; + let enc1, enc2, enc3, enc4; + let i = 0; + value = value.replace('-', '+').replace('_', '/'); + while (i < value.length) { + enc1 = key.indexOf(value.charAt(i++)); + enc2 = key.indexOf(value.charAt(i++)); + enc3 = key.indexOf(value.charAt(i++)); + enc4 = key.indexOf(value.charAt(i++)); + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + base64 = base64 + String.fromCharCode(chr1); + if (enc3 != 64 && chr2 != 0) { + base64 = base64 + String.fromCharCode(chr2); + } + if (enc4 != 64 && chr3 != 0) { + base64 = base64 + String.fromCharCode(chr3); + } + } + return base64; + } + /** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ + class Deferred { + constructor() { + this.promise = new Deferred.promiseConstructor((res, rej) => { + this.resolve = res; + this.reject = rej; + }); + } + } + Deferred.promiseConstructor = Promise; + // Taken from: https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library + function decodeJWTPayload(token) { + // Regex checks for base64url format + const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i; + const parts = token.split('.'); + if (parts.length !== 3) { + throw new Error('JWT is not valid: not a JWT structure'); + } + if (!base64UrlRegex.test(parts[1])) { + throw new Error('JWT is not valid: payload is not in base64url format'); + } + const base64Url = parts[1]; + return JSON.parse(decodeBase64URL(base64Url)); + } + /** + * Creates a promise that resolves to null after some time. + */ + async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); + } + /** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ + function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; + } + function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); + } + // Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs + function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); + } + async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); + } + function base64urlencode(str) { + return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + } + async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== 'undefined' && + typeof crypto.subtle !== 'undefined' && + typeof TextEncoder !== 'undefined'; + if (!hasCryptoSupport) { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; + } + const hashed = await sha256(verifier); + return base64urlencode(hashed); + } + async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += '/PASSWORD_RECOVERY'; + } + await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + return [codeChallenge, codeChallengeMethod]; + } + /** Parses the API version which is 2YYY-MM-DD. */ + const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; + function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; + } + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; + } + try { + const date = new Date(`${apiVersion}T00:00:00.0Z`); + return date; + } + catch (e) { + return null; + } + } + + class AuthError extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + this.code = code; + } + } + function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; + } + class AuthApiError extends AuthError { + constructor(message, status, code) { + super(message, status, code); + this.name = 'AuthApiError'; + this.status = status; + this.code = code; + } + } + function isAuthApiError(error) { + return isAuthError(error) && error.name === 'AuthApiError'; + } + class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; + } + } + class CustomAuthError extends AuthError { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; + } + } + class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); + } + } + function isAuthSessionMissingError(error) { + return isAuthError(error) && error.name === 'AuthSessionMissingError'; + } + class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); + } + } + class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400, undefined); + } + } + class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } + } + class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } + } + class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status, undefined); + } + } + function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; + } + /** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ + class AuthWeakPasswordError extends CustomAuthError { + constructor(message, status, reasons) { + super(message, 'AuthWeakPasswordError', status, 'weak_password'); + this.reasons = reasons; + } + } + function isAuthWeakPasswordError(error) { + return isAuthError(error) && error.name === 'AuthWeakPasswordError'; + } + + var __rest$1 = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); + const NETWORK_ERROR_CODES = [502, 503, 504]; + async function handleError(error) { + var _a; + if (!looksLikeFetchResponse(error)) { + throw new AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } + catch (e) { + throw new AuthUnknownError(_getErrorMessage(e), e); + } + let errorCode = undefined; + const responseAPIVersion = parseResponseAPIVersion(error); + if (responseAPIVersion && + responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp && + typeof data === 'object' && + data && + typeof data.code === 'string') { + errorCode = data.code; + } + else if (typeof data === 'object' && data && typeof data.error_code === 'string') { + errorCode = data.error_code; + } + if (!errorCode) { + // Legacy support for weak password errors, when there were no error codes + if (typeof data === 'object' && + data && + typeof data.weak_password === 'object' && + data.weak_password && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); + } + } + else if (errorCode === 'weak_password') { + throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); + } + else if (errorCode === 'session_not_found') { + // The `session_id` inside the JWT does not correspond to a row in the + // `sessions` table. This usually means the user has signed out, has been + // deleted, or their session has somehow been terminated. + throw new AuthSessionMissingError(); + } + throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); + } + const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); + }; + async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[API_VERSION_HEADER_NAME]) { + headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name; + } + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; + } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; + } + async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, Object.assign({}, requestParams)); + } + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new AuthRetryableFetchError(_getErrorMessage(e), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } + catch (e) { + await handleError(e); + } + } + function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = expiresAt(data.expires_in); + } + } + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; + } + function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && + data.weak_password && + typeof data.weak_password === 'object' && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.message && + typeof data.weak_password.message === 'string' && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + response.data.weak_password = data.weak_password; + } + return response; + } + function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; + } + function _ssoResponse(data) { + return { data, error: null }; + } + function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest$1(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; + } + function _noResolveJsonResponse(data) { + return data; + } + /** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ + function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; + } + + var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + class GoTrueAdminApi { + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = resolveFetch(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = 'global') { + try { + await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await _request(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = __rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: _generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); + } + catch (error) { + if (isAuthError(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: _noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted (setting `deleted_at` to the current timestamp and disabling their account while preserving their data) from the auth schema. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + try { + return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + try { + const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + try { + const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + } + + /** + * Provides safe access to the globalThis.localStorage property. + */ + const localStorageAdapter = { + getItem: (key) => { + if (!supportsLocalStorage()) { + return null; + } + return globalThis.localStorage.getItem(key); + }, + setItem: (key, value) => { + if (!supportsLocalStorage()) { + return; + } + globalThis.localStorage.setItem(key, value); + }, + removeItem: (key) => { + if (!supportsLocalStorage()) { + return; + } + globalThis.localStorage.removeItem(key); + }, + }; + /** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ + function memoryLocalStorageAdapter(store = {}) { + return { + getItem: (key) => { + return store[key] || null; + }, + setItem: (key, value) => { + store[key] = value; + }, + removeItem: (key) => { + delete store[key]; + }, + }; + } + + /** + * https://mathiasbynens.be/notes/globalthis + */ + function polyfillGlobalThis() { + if (typeof globalThis === 'object') + return; + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; + } + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; + } + } + } + + /** + * @experimental + */ + const internals = { + /** + * @experimental + */ + debug: !!(globalThis && + supportsLocalStorage() && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), + }; + /** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + */ + class LockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } + } + class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { + } + /** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ + async function navigatorLock(name, acquireTimeout, fn) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); + } + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + }, acquireTimeout); + } + // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request + return await globalThis.navigator.locks.request(name, acquireTimeout === 0 + ? { + mode: 'exclusive', + ifAvailable: true, + } + : { + mode: 'exclusive', + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); + } + try { + return await fn(); + } + finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); + } + } + } + else { + if (acquireTimeout === 0) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); + } + throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } + else { + if (internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); + } + catch (e) { + console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); + } + } + // Browser is not following the Navigator LockManager spec, it + // returned a null lock when we didn't use ifAvailable. So we can + // pretend the lock is acquired in the name of backward compatibility + // and user experience and just run the function. + console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); + return await fn(); + } + } + }); + } + + polyfillGlobalThis(); // Make "globalThis" available + const DEFAULT_OPTIONS = { + url: GOTRUE_URL, + storageKey: STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, + hasCustomAuthorizationHeader: false, + }; + /** Current session will be checked for refresh at this interval. */ + const AUTO_REFRESH_TICK_DURATION = 30 * 1000; + /** + * A token refresh will be attempted this many ticks before the current session expires. */ + const AUTO_REFRESH_TICK_THRESHOLD = 3; + async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); + } + class GoTrueClient { + /** + * Create a new client for use in the browser. + */ + constructor(options) { + var _a, _b; + this.memoryStorage = null; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the the auth state is known and it's save to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.logger = console.log; + this.instanceID = GoTrueClient.nextInstanceID; + GoTrueClient.nextInstanceID += 1; + if (this.instanceID > 0 && isBrowser()) { + console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); + } + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === 'function') { + this.logger = settings.debug; + } + this.persistSession = settings.persistSession; + this.storageKey = settings.storageKey; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = resolveFetch(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + if (settings.lock) { + this.lock = settings.lock; + } + else if (isBrowser() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) { + this.lock = navigatorLock; + } + else { + this.lock = lockNoOp; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } + else { + if (supportsLocalStorage()) { + this.storage = localStorageAdapter; + } + else { + this.memoryStorage = {}; + this.storage = memoryLocalStorageAdapter(this.memoryStorage); + } + } + } + else { + this.memoryStorage = {}; + this.storage = memoryLocalStorageAdapter(this.memoryStorage); + } + if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); + } + _debug(...args) { + if (this.logDebugMessages) { + this.logger(`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + try { + const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false; + this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow); + if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) { + const { data, error } = await this._getSessionFromURL(isPKCEFlow); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + // hacky workaround to keep the existing session if there's an error returned from identity linking + // TODO: once error codes are ready, we should match against it instead of the message + if ((error === null || error === void 0 ? void 0 : error.message) === 'Identity is already linked' || + (error === null || error === void 0 ? void 0 : error.message) === 'Identity is already linked to another user') { + return { error }; + } + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { error }; + } + return { + error: new AuthUnknownError('Unexpected error during initialization', error), + }; + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + } + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials) { + var _a, _b, _c; + try { + const res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, + }, + xform: _sessionResponse, + }); + const { data, error } = res; + if (error || !data) { + return { data: { user: null, session: null }, error: error }; + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: _sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + } + else { + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + return { data: { user: null, session: null }, error: error }; + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponsePassword, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponsePassword, + }); + } + else { + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { + data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), + error, + }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); + } + async _exchangeCodeForSession(authCode) { + const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); + try { + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: _sessionResponse, + }); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + return { + data: { user: null, session: null, redirectType: null }, + error: new AuthInvalidTokenResponseError(), + }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null, redirectType: null }, error }; + } + throw error; + } + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + const { data, error } = res; + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { + data: { user: null, session: null }, + error: new AuthInvalidTokenResponseError(), + }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data, error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return { data: { user: null, session: null }, error }; + } + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number.'); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params) { + var _a, _b; + try { + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: _sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + throw new Error('An error occurred on token verification.'); + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + return await _request(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: _ssoResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); + } + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new AuthSessionMissingError(); + const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return { data: { user: null, session: null }, error }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return { data: { user: null, session: null }, error }; + } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result) => { + return result; + }); + }); + return result; + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (this.lockAcquired) { + const last = this.pendingInLock.length + ? this.pendingInLock[this.pendingInLock.length - 1] + : Promise.resolve(); + const result = (async () => { + await last; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + await result; + // keep draining the queue until there's nothing to wait on + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + this.lockAcquired = false; + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + finally { + this._debug('#_useSession', 'end'); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (!this.lockAcquired) { + this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await getItemAsync(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + const hasExpired = currentSession.expires_at + ? currentSession.expires_at <= Date.now() / 1000 + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + if (this.storage.isServer) { + let suppressWarning = this.suppressGetSessionWarning; + const proxySession = new Proxy(currentSession, { + get: (target, prop, receiver) => { + if (!suppressWarning && prop === 'user') { + // only show warning when the user object is being accessed from the server + console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); + suppressWarning = true; // keeps this proxy instance from logging additional warnings + this.suppressGetSessionWarning = true; // keeps this client's future proxy instances from warning + } + return Reflect.get(target, prop, receiver); + }, + }); + currentSession = proxySession; + } + return { data: { session: currentSession }, error: null }; + } + const { session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { session: null }, error }; + } + return { data: { session }, error: null }; + } + finally { + this._debug('#__loadSession()', 'end'); + } + } + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + return result; + } + async _getUser(jwt) { + try { + if (jwt) { + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: _userResponse, + }); + } + return await this._useSession(async (result) => { + var _a, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + // returns an error if there is no access_token or custom authorization header + if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new AuthSessionMissingError() }; + } + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, + xform: _userResponse, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + if (isAuthSessionMissingError(error)) { + // JWT contains a `session_id` which does not correspond to an active + // session in the database, indicating the user is signed out. + await this._removeSession(); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); + } + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce' && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: _userResponse, + }); + if (userError) + throw userError; + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return { data: { user: session.user }, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Decodes a JWT (without performing any validation). + */ + _decodeJWT(jwt) { + return decodeJWTPayload(jwt); + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); + } + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const payload = decodeJWTPayload(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { user: null, session: null }, error: error }; + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user: session.user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { session: null, user: null }, error }; + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); + } + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new AuthSessionMissingError(); + } + const { session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { user: null, session: null }, error: error }; + } + if (!session) { + return { data: { user: null, session: null }, error: null }; + } + return { data: { user: session.user, session }, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(isPKCEFlow) { + try { + if (!isBrowser()) + throw new AuthImplicitGrantRedirectError('No browser detected.'); + if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) { + throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + else if (this.flowType == 'pkce' && !isPKCEFlow) { + throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + const params = parseParametersFromURL(window.location.href); + if (isPKCEFlow) { + if (!params.code) + throw new AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this._exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + if (params.error || params.error_description || params.error_code) { + throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); + } + else if (timeNow - issuedAt < 0) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return { data: { session, redirectType: params.type }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { session: null, redirectType: null }, error }; + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantFlow() { + const params = parseParametersFromURL(window.location.href); + return !!(isBrowser() && (params.access_token || params.error_description)); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCEFlow() { + const params = parseParametersFromURL(window.location.href); + const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options = { scope: 'global' }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); + } + async _signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return { error: sessionError }; + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!(isAuthApiError(error) && + (error.status === 404 || error.status === 401 || error.status === 403))) { + return { error }; + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + return { error: null }; + }); + } + /** + * Receive a notification every time an auth event happens. + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback) { + const id = uuid(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey, true // isPasswordRecovery + ); + } + try { + return await _request(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities() { + var _a; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Links an oauth identity to an existing user. + * This method supports the PKCE flow. + */ + async linkIdentity(credentials) { + var _a; + try { + const { data, error } = await this._useSession(async (result) => { + var _a, _b, _c, _d, _e; + const { data, error } = result; + if (error) + throw error; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true, + }); + return await _request(this.fetch, 'GET', url, { + headers: this.headers, + jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, + }); + }); + if (error) + throw error; + if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { provider: credentials.provider, url: null }, error }; + } + throw error; + } + } + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await retryable(async (attempt) => { + if (attempt > 0) { + await sleep(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... + } + this._debug(debugName, 'refreshing attempt', attempt); + return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: _sessionResponse, + }); + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return (error && + isAuthRetryableFetchError(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION); + }); + } + catch (error) { + this._debug(debugName, 'error', error); + if (isAuthError(error)) { + return { data: { session: null, user: null }, error }; + } + throw error; + } + finally { + this._debug(debugName, 'end'); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if (isBrowser() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = await getItemAsync(this.storage, this.storageKey); + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const timeNow = Math.round(Date.now() / 1000); + const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!isAuthRetryableFetchError(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { session: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if (isAuthError(error)) { + const result = { session: null, error }; + if (!isAuthRetryableFetchError(error)) { + await this._removeSession(); + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + // _saveSession is always called whenever a new session has been acquired + // so we can safely suppress the warning returned by future getSession calls + this.suppressGetSessionWarning = true; + await setItemAsync(this.storage, this.storageKey, session); + } + async _removeSession() { + this._debug('#_removeSession()'); + await removeItemAsync(this.storage, this.storageKey); + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-ignore + } + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-ignore + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + }); + } + catch (e) { + if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) { + this._debug('auto refresh token tick lock not available'); + } + else { + throw e; + } + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + // called when the visibility has changed, i.e. the browser + // transitioned from hidden -> visible so we need to see if the session + // should be recovered immediately... but to do that we need to acquire + // the lock first asynchronously + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== 'visible') { + this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); + // visibility has changed while waiting for the lock, abort + return; + } + // recover the session + await this._recoverAndRefresh(); + }); + } + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join('&')}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#enroll} + */ + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' ? { phone: params.phone } : { issuer: params.issuer })); + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return { data: null, error }; + } + // TODO: Remove once: https://github.com/supabase/auth/pull/1717 is deployed + if (params.factorType === 'phone') { + delete data.totp; + } + if (params.factorType === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return { data, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#verify} + */ + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body: { code: params.code, challenge_id: params.challengeId }, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return { data: null, error }; + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return { data, error }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challenge} + */ + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + return await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + body: { channel: params.channel }, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + // both _challenge and _verify independently acquire the lock, so no need + // to acquire it here + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return { data: null, error: challengeError }; + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + // use #getUser instead of #_getUser as the former acquires a lock + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const factors = (user === null || user === void 0 ? void 0 : user.factors) || []; + const totp = factors.filter((factor) => factor.factor_type === 'totp' && factor.status === 'verified'); + const phone = factors.filter((factor) => factor.factor_type === 'phone' && factor.status === 'verified'); + return { + data: { + all: factors, + totp, + phone, + }, + error: null, + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + return this._acquireLock(-1, async () => { + return await this._useSession(async (result) => { + var _a, _b; + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const payload = this._decodeJWT(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + }); + }); + } + } + GoTrueClient.nextInstanceID = 0; + + const AuthAdminApi = GoTrueAdminApi; + + const AuthClient = GoTrueClient; + + class SupabaseAuthClient extends AuthClient { + constructor(options) { + super(options); + } + } + + 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()); + }); + }; + /** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ + class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + if (!supabaseUrl) + throw new Error('supabaseUrl is required.'); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + const _supabaseUrl = stripTrailingSlash(supabaseUrl); + this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws'); + this.authUrl = `${_supabaseUrl}/auth/v1`; + this.storageUrl = `${_supabaseUrl}/storage/v1`; + this.functionsUrl = `${_supabaseUrl}/functions/v1`; + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: DEFAULT_DB_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: DEFAULT_GLOBAL_OPTIONS, + }; + const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } + else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + }, + }); + } + this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers }, settings.realtime)); + this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch, + }); + if (!settings.accessToken) { + this._listenForAuthEvents(); + } + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new FunctionsClient(this.functionsUrl, { + headers: this.headers, + customFetch: this.fetch, + }); + } + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + get storage() { + return new StorageClient(this.storageUrl, this.headers, this.fetch); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return this.rest.schema(schema); + } + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = {}) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + _getAccessToken() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + if (this.accessToken) { + return yield this.accessToken(); + } + const { data } = yield this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : null; + }); + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, storageKey, flowType, lock, debug, }, headers, fetch) { + var _a; + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient({ + url: this.authUrl, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + flowType, + lock, + debug, + fetch, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: (_a = 'Authorization' in this.headers) !== null && _a !== void 0 ? _a : false, + }); + } + _initRealtimeClient(options) { + return new RealtimeClient(this.realtimeUrl, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + let data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + // Token has changed + this.realtime.setAuth(token !== null && token !== void 0 ? token : null); + this.changedAccessToken = token; + } + else if (event === 'SIGNED_OUT') { + // Token is removed + this.realtime.setAuth(this.supabaseKey); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } + } + } + + /** + * Creates a new Supabase Client. + */ + const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient(supabaseUrl, supabaseKey, options); + }; + + const __esModule = true; + + exports.AuthAdminApi = AuthAdminApi; + exports.AuthApiError = AuthApiError; + exports.AuthClient = AuthClient; + exports.AuthError = AuthError; + exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; + exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; + exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; + exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; + exports.AuthRetryableFetchError = AuthRetryableFetchError; + exports.AuthSessionMissingError = AuthSessionMissingError; + exports.AuthUnknownError = AuthUnknownError; + exports.AuthWeakPasswordError = AuthWeakPasswordError; + exports.Buffer = Buffer; + exports.CustomAuthError = CustomAuthError; + exports.FunctionsError = FunctionsError; + exports.FunctionsFetchError = FunctionsFetchError; + exports.FunctionsHttpError = FunctionsHttpError; + exports.FunctionsRelayError = FunctionsRelayError; + exports.GoTrueAdminApi = GoTrueAdminApi; + exports.GoTrueClient = GoTrueClient; + exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; + exports.REALTIME_CHANNEL_STATES = REALTIME_CHANNEL_STATES; + exports.RealtimeChannel = RealtimeChannel; + exports.RealtimeClient = RealtimeClient; + exports.RealtimePresence = RealtimePresence; + exports.SupabaseClient = SupabaseClient; + exports.__esModule = __esModule; + exports._polyfillNode_buffer = _polyfillNode_buffer; + exports.createClient = createClient; + exports.getAugmentedNamespace = getAugmentedNamespace; + exports.global = global$1; + exports.internals = internals; + exports.isAuthApiError = isAuthApiError; + exports.isAuthError = isAuthError; + exports.isAuthRetryableFetchError = isAuthRetryableFetchError; + exports.isAuthSessionMissingError = isAuthSessionMissingError; + exports.isAuthWeakPasswordError = isAuthWeakPasswordError; + exports.isBuffer = isBuffer; + exports.navigatorLock = navigatorLock; + +})); diff --git a/packages/ui5-tooling-modules/test/__snap__/d726ec84/@ui5/webcomponents/dist/Panel.js b/packages/ui5-tooling-modules/test/__snap__/d726ec84/@ui5/webcomponents/dist/Panel.js index 75ca7482c..02419066c 100644 --- a/packages/ui5-tooling-modules/test/__snap__/d726ec84/@ui5/webcomponents/dist/Panel.js +++ b/packages/ui5-tooling-modules/test/__snap__/d726ec84/@ui5/webcomponents/dist/Panel.js @@ -1,206 +1,5 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/core/webc/WebComponentRenderer', 'sap/ui/core/webc/WebComponent'], (function (DataType, hyphenate, WebComponentRenderer, WebComponentBaseClass) { 'use strict'; - /** - * @license - * Copyright 2023 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */ - /** - * Map of ARIAMixin properties to attributes - */ - // Shim the global element internals object - // Methods should be fine as noops and properties can generally - // be while on the server. - const ElementInternalsShim = class ElementInternals { - get shadowRoot() { - // Grab the shadow root instance from the Element shim - // to ensure that the shadow root is always available - // to the internals instance even if the mode is 'closed' - return this.__host - .__shadowRoot; - } - constructor(_host) { - this.ariaAtomic = ''; - this.ariaAutoComplete = ''; - this.ariaBrailleLabel = ''; - this.ariaBrailleRoleDescription = ''; - this.ariaBusy = ''; - this.ariaChecked = ''; - this.ariaColCount = ''; - this.ariaColIndex = ''; - this.ariaColSpan = ''; - this.ariaCurrent = ''; - this.ariaDescription = ''; - this.ariaDisabled = ''; - this.ariaExpanded = ''; - this.ariaHasPopup = ''; - this.ariaHidden = ''; - this.ariaInvalid = ''; - this.ariaKeyShortcuts = ''; - this.ariaLabel = ''; - this.ariaLevel = ''; - this.ariaLive = ''; - this.ariaModal = ''; - this.ariaMultiLine = ''; - this.ariaMultiSelectable = ''; - this.ariaOrientation = ''; - this.ariaPlaceholder = ''; - this.ariaPosInSet = ''; - this.ariaPressed = ''; - this.ariaReadOnly = ''; - this.ariaRequired = ''; - this.ariaRoleDescription = ''; - this.ariaRowCount = ''; - this.ariaRowIndex = ''; - this.ariaRowSpan = ''; - this.ariaSelected = ''; - this.ariaSetSize = ''; - this.ariaSort = ''; - this.ariaValueMax = ''; - this.ariaValueMin = ''; - this.ariaValueNow = ''; - this.ariaValueText = ''; - this.role = ''; - this.form = null; - this.labels = []; - this.states = new Set(); - this.validationMessage = ''; - this.validity = {}; - this.willValidate = true; - this.__host = _host; - } - checkValidity() { - // TODO(augustjk) Consider actually implementing logic. - // See https://github.com/lit/lit/issues/3740 - console.warn('`ElementInternals.checkValidity()` was called on the server.' + - 'This method always returns true.'); - return true; - } - reportValidity() { - return true; - } - setFormValue() { } - setValidity() { } - }; - - const attributes = new WeakMap(); - const attributesForElement = element => { - let attrs = attributes.get(element); - if (attrs === undefined) { - attributes.set(element, attrs = new Map()); - } - return attrs; - }; - const ElementShim = class Element { - constructor() { - this.__shadowRootMode = null; - this.__shadowRoot = null; - this.__internals = null; - } - get attributes() { - return Array.from(attributesForElement(this)).map(([name, value]) => ({ - name, - value - })); - } - get shadowRoot() { - if (this.__shadowRootMode === "closed") { - return null; - } - return this.__shadowRoot; - } - get localName() { - return this.constructor.__localName; - } - get tagName() { - return this.localName?.toUpperCase(); - } - setAttribute(name, value) { - attributesForElement(this).set(name, String(value)); - } - removeAttribute(name) { - attributesForElement(this).delete(name); - } - toggleAttribute(name, force) { - if (this.hasAttribute(name)) { - if (force === undefined || !force) { - this.removeAttribute(name); - return false; - } - } else { - if (force === undefined || force) { - this.setAttribute(name, ""); - return true; - } else { - return false; - } - } - return true; - } - hasAttribute(name) { - return attributesForElement(this).has(name); - } - attachShadow(init) { - const shadowRoot = { - host: this - }; - this.__shadowRootMode = init.mode; - if (init && init.mode === "open") { - this.__shadowRoot = shadowRoot; - } - return shadowRoot; - } - attachInternals() { - if (this.__internals !== null) { - throw new Error(`Failed to execute 'attachInternals' on 'HTMLElement': ` + `ElementInternals for the specified element was already attached.`); - } - const internals = new ElementInternalsShim(this); - this.__internals = internals; - return internals; - } - getAttribute(name) { - const value = attributesForElement(this).get(name); - return value ?? null; - } - }; - const ElementShimWithRealType = ElementShim; - const HTMLElementShim = class HTMLElement extends ElementShim {}; - const HTMLElementShimWithRealType = HTMLElementShim; - const CustomElementRegistryShim = class CustomElementRegistry { - constructor() { - this.__definitions = new Map(); - } - define(name, ctor) { - if (this.__definitions.has(name)) { - { - throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': ` + `the name "${name}" has already been used with this registry`); - } - } - ctor.__localName = name; - this.__definitions.set(name, { - ctor, - observedAttributes: ctor.observedAttributes ?? [] - }); - } - get(name) { - const definition = this.__definitions.get(name); - return definition?.ctor; - } - }; - const CustomElementRegistryShimWithRealType = CustomElementRegistryShim; - const customElements$1 = new CustomElementRegistryShimWithRealType(); - - /* eslint-disable max-classes-per-file */ - globalThis.HTMLElement ??= HTMLElementShimWithRealType; - globalThis.Element ??= ElementShimWithRealType; - globalThis.customElements ??= customElements$1; - class NodeShim { - } - globalThis.Node ??= NodeShim; - class FileListShim { - } - globalThis.FileList ??= FileListShim; - var class2type = {}; var hasOwn = class2type.hasOwnProperty; var toString = class2type.toString; @@ -2943,7 +2742,7 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - var t$1;const i$1=globalThis,s$2=i$1.trustedTypes,e$3=s$2?s$2.createPolicy("lit-html",{createHTML:t=>t}):void 0,o$2="$lit$",n$1=`lit$${(Math.random()+"").slice(9)}$`,l$3="?"+n$1,h=`<${l$3}>`,r$1=void 0===i$1.document?{createTreeWalker:()=>({})}:document,u$2=()=>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$2="[ \t\n\f\r]",f$1=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,_=/-->/g,m$1=/>/g,p$1=RegExp(`>|${a$2}(?:([^\\s"'>=/]+)(${a$2}*=${a$2}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),g=/'/g,$=/"/g,y=/^(?:script|style|textarea|title)$/i,x=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),T=x(1),b=x(2),w=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$3?e$3.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 x=u===p$1&&t[i+1].startsWith("/>")?" ":"";r+=u===f$1?s+h:v>=0?(e.push(d),s.slice(0,v)+o$2+s.slice(v)+n$1+x):s+n$1+(-2===v?(e.push(void 0),i):x);}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$2?s$2.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!==w,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 k(i.insertBefore(u$2(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; + var t$1;const i$1=window,s$2=i$1.trustedTypes,e$3=s$2?s$2.createPolicy("lit-html",{createHTML:t=>t}):void 0,o$2="$lit$",n$1=`lit$${(Math.random()+"").slice(9)}$`,l$3="?"+n$1,h=`<${l$3}>`,r$1=document,u$2=()=>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$2="[ \t\n\f\r]",f$1=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,_=/-->/g,m$1=/>/g,p$1=RegExp(`>|${a$2}(?:([^\\s"'>=/]+)(${a$2}*=${a$2}*(?:[^ \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$3?e$3.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$2+s.slice(v)+n$1+w):s+n$1+(-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$2?s$2.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$2(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l}; /** * @license @@ -2956,20 +2755,20 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const {I:l$2}=Z,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$2(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$1={},a$1=(o,l=s$1)=>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$2}=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$2(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$1={},a$1=(o,l=s$1)=>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;}}; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ - 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=e$2(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=m(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$1=[];let y,x,j=0,k=a.length-1,w$1=0,A=p$1.length-1;for(;j<=k&&w$1<=A;)if(null===a[j])j++;else if(null===a[k])k--;else if(h[j]===v[w$1])m$1[w$1]=f(a[j],p$1[w$1]),j++,w$1++;else if(h[k]===v[A])m$1[A]=f(a[k],p$1[A]),k--,A--;else if(h[j]===v[A])m$1[A]=f(a[j],p$1[A]),c$1(s,m$1[A+1],a[j]),j++,A--;else if(h[k]===v[w$1])m$1[w$1]=f(a[k],p$1[w$1]),c$1(s,a[j],a[k]),k--,w$1++;else if(void 0===y&&(y=u$1(v,w$1,A),x=u$1(h,j,k)),y.has(h[j]))if(y.has(h[k])){const e=x.get(v[w$1]),t=void 0!==e?a[e]:null;if(null===t){const e=c$1(s,a[j]);f(e,p$1[w$1]),m$1[w$1]=e;}else m$1[w$1]=f(t,p$1[w$1]),c$1(s,a[j],t),a[e]=null;w$1++;}else p(a[k]),k--;else p(a[j]),j++;for(;w$1<=A;){const e=c$1(s,m$1[A+1]);f(e,p$1[w$1]),m$1[w$1++]=e;}for(;j<=k;){const e=a[j++];null!==e&&p(e);}return this.ut=v,a$1(s,m$1),w}}); + 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=e$2(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=m(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$1=[];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$1[w]=f(a[j],p$1[w]),j++,w++;else if(h[k]===v[A])m$1[A]=f(a[k],p$1[A]),k--,A--;else if(h[j]===v[A])m$1[A]=f(a[j],p$1[A]),c$1(s,m$1[A+1],a[j]),j++,A--;else if(h[k]===v[w])m$1[w]=f(a[k],p$1[w]),c$1(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$1(s,a[j]);f(e,p$1[w]),m$1[w]=e;}else m$1[w]=f(t,p$1[w]),c$1(s,a[j],t),a[e]=null;w++;}else p(a[k]),k--;else p(a[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[j++];null!==e&&p(e);}return this.ut=v,a$1(s,m$1),T}}); /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const o$1=e$2(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 w}}); + */const o$1=e$2(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}}); // @ts-nocheck /* eslint-disable */ @@ -3036,7 +2835,7 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor } } } - return w; + return T; } } const styleMap = e$2(StyleMapDirective); @@ -3051,11 +2850,11 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */let e$1 = 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===w)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$1.directiveName="unsafeHTML",e$1.resultType=1; + */let e$1 = 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$1.directiveName="unsafeHTML",e$1.resultType=1; const effectiveHtml = (strings, ...values) => { const litStatic = getFeature("LitStatic"); - const fn = litStatic ? litStatic.html : T; + const fn = litStatic ? litStatic.html : x; return fn(strings, ...values); }; const effectiveSvg = (strings, ...values) => { @@ -3068,7 +2867,7 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor if (openUI5Enablement) { templateResult = openUI5Enablement.wrapTemplateResultInBusyMarkup(effectiveHtml, options.host, templateResult); } - B(templateResult, container, options); + D(templateResult, container, options); }; const scopeTag = (tag, tags, suffix) => { const litStatic = getFeature("LitStatic"); @@ -5173,7 +4972,7 @@ sap.ui.define(['sap/ui/base/DataType', 'sap/base/strings/hyphenate', 'sap/ui/cor * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */const e=Symbol.for(""),l=t=>{if((null==t?void 0:t.r)===e)return null==t?void 0:t._$litStatic$},o=t=>({_$litStatic$:t,r:e}),s=new Map,a=t=>(r,...e)=>{const o=e.length;let i,a;const n=[],u=[];let c,$=0,f=!1;for(;${if((null==t?void 0:t.r)===e)return null==t?void 0:t._$litStatic$},o=t=>({_$litStatic$:t,r:e}),s=new Map,a=t=>(r,...e)=>{const o=e.length;let i,a;const n=[],u=[];let c,$=0,f=!1;for(;$ val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(exports.util || (exports.util = {})); + exports.objectUtil = void 0; + (function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; + })(exports.objectUtil || (exports.objectUtil = {})); + const ZodParsedType = exports.util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", + ]); + const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; - var lib = {}; + const ZodIssueCode = exports.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", + ]); + const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); + }; + class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + } + ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; + }; - var external = {}; - - var errors = {}; - - var en = {}; - - var util = {}; - - (function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; - var util; - (function (util) { - util.assertEqual = (val) => val; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; - })(util = exports.util || (exports.util = {})); - (function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; - })(exports.objectUtil || (exports.objectUtil = {})); - exports.ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", - ]); - const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return exports.ZodParsedType.undefined; - case "string": - return exports.ZodParsedType.string; - case "number": - return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; - case "boolean": - return exports.ZodParsedType.boolean; - case "function": - return exports.ZodParsedType.function; - case "bigint": - return exports.ZodParsedType.bigint; - case "symbol": - return exports.ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return exports.ZodParsedType.array; - } - if (data === null) { - return exports.ZodParsedType.null; - } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { - return exports.ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return exports.ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return exports.ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return exports.ZodParsedType.date; - } - return exports.ZodParsedType.object; - default: - return exports.ZodParsedType.unknown; - } - }; - exports.getParsedType = getParsedType; - } (util)); - - var ZodError$1 = {}; - - Object.defineProperty(ZodError$1, "__esModule", { value: true }); - ZodError$1.ZodError = ZodError$1.quotelessJson = ZodError$1.ZodIssueCode = void 0; - const util_1$1 = util; - ZodError$1.ZodIssueCode = util_1$1.util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", - ]); - const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); - }; - ZodError$1.quotelessJson = quotelessJson; - class ZodError extends Error { - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - get errors() { - return this.issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util_1$1.util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } - } - ZodError$1.ZodError = ZodError; - ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; - }; - - Object.defineProperty(en, "__esModule", { value: true }); - const util_1 = util; - const ZodError_1 = ZodError$1; - const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodError_1.ZodIssueCode.invalid_type: - if (issue.received === util_1.ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodError_1.ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; - break; - case ZodError_1.ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; - break; - case ZodError_1.ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; - break; - case ZodError_1.ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodError_1.ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodError_1.ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodError_1.ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodError_1.ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util_1.util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodError_1.ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact + const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + exports.util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodError_1.ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodError_1.ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util_1.util.assertNever(issue); - } - return { message }; - }; - en.default = errorMap; - - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(errors, "__esModule", { value: true }); - errors.getErrorMap = errors.setErrorMap = errors.defaultErrorMap = void 0; - const en_1 = __importDefault(en); - errors.defaultErrorMap = en_1.default; - let overrideErrorMap = en_1.default; - function setErrorMap(map) { - overrideErrorMap = map; - } - errors.setErrorMap = setErrorMap; - function getErrorMap() { - return overrideErrorMap; - } - errors.getErrorMap = getErrorMap; - - var parseUtil = {}; - - (function (exports) { - var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; - const errors_1 = errors; - const en_1 = __importDefault(en); - const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; - }; - exports.makeIssue = makeIssue; - exports.EMPTY_PATH = []; - function addIssueToContext(ctx, issueData) { - const overrideMap = (0, errors_1.getErrorMap)(); - const issue = (0, exports.makeIssue)({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_1.default ? undefined : en_1.default, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); - } - exports.addIssueToContext = addIssueToContext; - class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return exports.INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return exports.INVALID; - if (value.status === "aborted") - return exports.INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } - } - exports.ParseStatus = ParseStatus; - exports.INVALID = Object.freeze({ - status: "aborted", - }); - const DIRTY = (value) => ({ status: "dirty", value }); - exports.DIRTY = DIRTY; - const OK = (value) => ({ status: "valid", value }); - exports.OK = OK; - const isAborted = (x) => x.status === "aborted"; - exports.isAborted = isAborted; - const isDirty = (x) => x.status === "dirty"; - exports.isDirty = isDirty; - const isValid = (x) => x.status === "valid"; - exports.isValid = isValid; - const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - exports.isAsync = isAsync; - } (parseUtil)); - - var typeAliases = {}; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + exports.util.assertNever(issue); + } + return { message }; + }; - Object.defineProperty(typeAliases, "__esModule", { value: true }); + let overrideErrorMap = errorMap; + function setErrorMap(map) { + overrideErrorMap = map; + } + function getErrorMap() { + return overrideErrorMap; + } - var types = {}; + const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; + } + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; + }; + const EMPTY_PATH = []; + function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === errorMap ? undefined : errorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); + } + class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + } + const INVALID = Object.freeze({ + status: "aborted", + }); + const DIRTY = (value) => ({ status: "dirty", value }); + const OK = (value) => ({ status: "valid", value }); + const isAborted = (x) => x.status === "aborted"; + const isDirty = (x) => x.status === "dirty"; + const isValid = (x) => x.status === "valid"; + const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - var errorUtil = {}; + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + function __classPrivateFieldGet(receiver, state, kind, f) { + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return state.get(receiver); + } + + function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (state.set(receiver, value)), value; + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; - (function (exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.errorUtil = void 0; - (function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; - })(exports.errorUtil || (exports.errorUtil = {})); - } (errorUtil)); + var errorUtil; + (function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; + })(errorUtil || (errorUtil = {})); - (function (exports) { - var __classPrivateFieldGet = (commonjsGlobal && commonjsGlobal.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - var __classPrivateFieldSet = (commonjsGlobal && commonjsGlobal.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - var _ZodEnum_cache, _ZodNativeEnum_cache; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.datetimeRegex = exports.ZodType = void 0; - exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = exports.date = void 0; - const errors_1 = errors; - const errorUtil_1 = errorUtil; - const parseUtil_1 = parseUtil; - const util_1 = util; - const ZodError_1 = ZodError$1; - class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } - } - const handleResult = (ctx, result) => { - if ((0, parseUtil_1.isValid)(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError_1.ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } - }; - function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; - } - class ZodType { - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - get description() { - return this._def.description; - } - _getType(input) { - return (0, util_1.getParsedType)(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new parseUtil_1.ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if ((0, parseUtil_1.isAsync)(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodError_1.ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this, this._def); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } - } - exports.ZodType = ZodType; - exports.Schema = ZodType; - exports.ZodSchema = ZodType; - const cuidRegex = /^c[^\s-]{8,}$/i; - const cuid2Regex = /^[0-9a-z]+$/; - const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; - // const uuidRegex = - // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; - const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; - const nanoidRegex = /^[a-z0-9_-]{21}$/i; - const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - // from https://stackoverflow.com/a/46181/1550155 - // old version: too slow, didn't support unicode - // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; - //old email regex - // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; - // eslint-disable-next-line - // const emailRegex = - // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; - // const emailRegex = - // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - // const emailRegex = - // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; - const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; - // const emailRegex = - // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; - // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression - const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; - let emojiRegex; - // faster, simpler, safer - const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; - // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript - const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - // simple - // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; - // no leap year validation - // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; - // with leap year validation - const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; - const dateRegex = new RegExp(`^${dateRegexSource}$`); - function timeRegexSource(args) { - // let regex = `\\d{2}:\\d{2}:\\d{2}`; - let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; - if (args.precision) { - regex = `${regex}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - regex = `${regex}(\\.\\d+)?`; - } - return regex; - } - function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); - } - // Adapted from https://stackoverflow.com/a/3143231 - function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); - } - exports.datetimeRegex = datetimeRegex; - function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; - } - class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.string, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "email", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "emoji", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "uuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "nanoid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid2", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ulid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "regex", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "duration", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ip", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "base64", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodError_1.ZodIssueCode.invalid_string, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); - } - datetime(options) { - var _a, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); - } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil_1.errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - /** - * @deprecated Use z.string().min(1) instead. - * @see {@link ZodString.min} - */ - nonempty(message) { - return this.min(1, errorUtil_1.errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - } - exports.ZodString = ZodString; - ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); - }; - // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 - function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); - } - class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.number, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util_1.util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil_1.errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil_1.errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); - } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } - } - exports.ZodNumber = ZodNumber; - ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); - }; - class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - input.data = BigInt(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.bigint) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.bigint, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - } - exports.ZodBigInt = ZodBigInt; - ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); - }; - class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.boolean, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodBoolean = ZodBoolean; - ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); - }; - class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.date, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_date, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } - } - exports.ZodDate = ZodDate; - ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); - }; - class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.symbol, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodSymbol = ZodSymbol; - ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); - }; - class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.undefined, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodUndefined = ZodUndefined; - ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); - }; - class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.null, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodNull = ZodNull; - ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); - }; - class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; - } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodAny = ZodAny; - ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); - }; - class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; - } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodUnknown = ZodUnknown; - ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); - }; - class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.never, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - } - exports.ZodNever = ZodNever; - ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); - }; - class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.void, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - } - exports.ZodVoid = ZodVoid; - ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); - }; - class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return parseUtil_1.ParseStatus.mergeArray(status, result); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return parseUtil_1.ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - nonempty(message) { - return this.min(1, message); - } - } - exports.ZodArray = ZodArray; - ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); - }; - function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } - } - class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util_1.util.objectKeys(shape); - return (this._cached = { shape, keys }); - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil_1.errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - util_1.util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - omit(mask) { - const shape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - required(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util_1.util.objectKeys(this.shape)); - } - } - exports.ZodObject = ZodObject; - ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); - }; - ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); - }; - ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); - }; - class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - // return invalid - const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); - } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } - } - get options() { - return this._def.options; - } - } - exports.ZodUnion = ZodUnion; - ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); - }; - ///////////////////////////////////////////////////// - ///////////////////////////////////////////////////// - ////////// ////////// - ////////// ZodDiscriminatedUnion ////////// - ////////// ////////// - ///////////////////////////////////////////////////// - ///////////////////////////////////////////////////// - const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } - else if (type instanceof ZodLiteral) { - return [type.value]; - } - else if (type instanceof ZodEnum) { - return type.options; - } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util_1.util.objectValues(type.enum); - } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } - else if (type instanceof ZodUndefined) { - return [undefined]; - } - else if (type instanceof ZodNull) { - return [null]; - } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } - else { - return []; - } - }; - class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); - } - } - exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; - function mergeValues(a, b) { - const aType = (0, util_1.getParsedType)(a); - const bType = (0, util_1.getParsedType)(b); - if (a === b) { - return { valid: true, data: a }; - } - else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { - const bKeys = util_1.util.objectKeys(b); - const sharedKeys = util_1.util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - else if (aType === util_1.ZodParsedType.date && - bType === util_1.ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; - } - else { - return { valid: false }; - } - } - class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { - return parseUtil_1.INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_intersection_types, - }); - return parseUtil_1.INVALID; - } - if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } - } - } - exports.ZodIntersection = ZodIntersection; - ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); - }; - class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (ctx.data.length < this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return parseUtil_1.INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return parseUtil_1.ParseStatus.mergeArray(status, results); - }); - } - else { - return parseUtil_1.ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); - } - } - exports.ZodTuple = ZodTuple; - ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); - }; - class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (ctx.common.async) { - return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); - } - } - exports.ZodRecord = ZodRecord; - class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.map) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.map, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } - } - exports.ZodMap = ZodMap; - ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); - }; - class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.set) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.set, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return parseUtil_1.INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } - } - exports.ZodSet = ZodSet; - ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); - }; - class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.function) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.function, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - function makeArgsIssue(args, error) { - return (0, parseUtil_1.makeIssue)({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return (0, parseUtil_1.makeIssue)({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(async function (...args) { - const error = new ZodError_1.ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); - } - } - exports.ZodFunction = ZodFunction; - class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } - } - exports.ZodLazy = ZodLazy; - ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); - }; - class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } - } - exports.ZodLiteral = ZodLiteral; - ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); - }; - function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); - } - class ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); - } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, - }); - } - } - exports.ZodEnum = ZodEnum; - _ZodEnum_cache = new WeakMap(); - ZodEnum.create = createZodEnum; - class ZodNativeEnum extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== util_1.ZodParsedType.string && - ctx.parsedType !== util_1.ZodParsedType.number) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util_1.util.getValidEnumValues(this._def.values)), "f"); - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get enum() { - return this._def.values; - } - } - exports.ZodNativeEnum = ZodNativeEnum; - _ZodNativeEnum_cache = new WeakMap(); - ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); - }; - class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.promise && - ctx.common.async === false) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.promise, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const promisified = ctx.parsedType === util_1.ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return (0, parseUtil_1.OK)(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } - } - exports.ZodPromise = ZodPromise; - ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); - }; - class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - (0, parseUtil_1.addIssueToContext)(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!(0, parseUtil_1.isValid)(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!(0, parseUtil_1.isValid)(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); - } - } - util_1.util.assertNever(effect); - } - } - exports.ZodEffects = ZodEffects; - exports.ZodTransformer = ZodEffects; - ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); - }; - ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); - }; - class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.undefined) { - return (0, parseUtil_1.OK)(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } - } - exports.ZodOptional = ZodOptional; - ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); - }; - class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.null) { - return (0, parseUtil_1.OK)(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } - } - exports.ZodNullable = ZodNullable; - ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); - }; - class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === util_1.ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - removeDefault() { - return this._def.innerType; - } - } - exports.ZodDefault = ZodDefault; - ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); - }; - class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if ((0, parseUtil_1.isAsync)(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - removeCatch() { - return this._def.innerType; - } - } - exports.ZodCatch = ZodCatch; - ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); - }; - class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.nan, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; - } - } - exports.ZodNaN = ZodNaN; - ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); - }; - exports.BRAND = Symbol("zod_brand"); - class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } - } - exports.ZodBranded = ZodBranded; - class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return (0, parseUtil_1.DIRTY)(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } - } - exports.ZodPipeline = ZodPipeline; - class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if ((0, parseUtil_1.isValid)(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return (0, parseUtil_1.isAsync)(result) - ? result.then((data) => freeze(data)) - : freeze(result); - } - unwrap() { - return this._def.innerType; - } - } - exports.ZodReadonly = ZodReadonly; - ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); - }; - function custom(check, params = {}, - /** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ - fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - if (!check(data)) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - const p2 = typeof p === "string" ? { message: p } : p; - ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); - } - }); - return ZodAny.create(); - } - exports.custom = custom; - exports.late = { - object: ZodObject.lazycreate, - }; - var ZodFirstPartyTypeKind; - (function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; - })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); - const instanceOfType = ( - // const instanceOfType = any>( - cls, params = { - message: `Input not instance of ${cls.name}`, - }) => custom((data) => data instanceof cls, params); - exports.instanceof = instanceOfType; - const stringType = ZodString.create; - exports.string = stringType; - const numberType = ZodNumber.create; - exports.number = numberType; - const nanType = ZodNaN.create; - exports.nan = nanType; - const bigIntType = ZodBigInt.create; - exports.bigint = bigIntType; - const booleanType = ZodBoolean.create; - exports.boolean = booleanType; - const dateType = ZodDate.create; - exports.date = dateType; - const symbolType = ZodSymbol.create; - exports.symbol = symbolType; - const undefinedType = ZodUndefined.create; - exports.undefined = undefinedType; - const nullType = ZodNull.create; - exports.null = nullType; - const anyType = ZodAny.create; - exports.any = anyType; - const unknownType = ZodUnknown.create; - exports.unknown = unknownType; - const neverType = ZodNever.create; - exports.never = neverType; - const voidType = ZodVoid.create; - exports.void = voidType; - const arrayType = ZodArray.create; - exports.array = arrayType; - const objectType = ZodObject.create; - exports.object = objectType; - const strictObjectType = ZodObject.strictCreate; - exports.strictObject = strictObjectType; - const unionType = ZodUnion.create; - exports.union = unionType; - const discriminatedUnionType = ZodDiscriminatedUnion.create; - exports.discriminatedUnion = discriminatedUnionType; - const intersectionType = ZodIntersection.create; - exports.intersection = intersectionType; - const tupleType = ZodTuple.create; - exports.tuple = tupleType; - const recordType = ZodRecord.create; - exports.record = recordType; - const mapType = ZodMap.create; - exports.map = mapType; - const setType = ZodSet.create; - exports.set = setType; - const functionType = ZodFunction.create; - exports.function = functionType; - const lazyType = ZodLazy.create; - exports.lazy = lazyType; - const literalType = ZodLiteral.create; - exports.literal = literalType; - const enumType = ZodEnum.create; - exports.enum = enumType; - const nativeEnumType = ZodNativeEnum.create; - exports.nativeEnum = nativeEnumType; - const promiseType = ZodPromise.create; - exports.promise = promiseType; - const effectsType = ZodEffects.create; - exports.effect = effectsType; - exports.transformer = effectsType; - const optionalType = ZodOptional.create; - exports.optional = optionalType; - const nullableType = ZodNullable.create; - exports.nullable = nullableType; - const preprocessType = ZodEffects.createWithPreprocess; - exports.preprocess = preprocessType; - const pipelineType = ZodPipeline.create; - exports.pipeline = pipelineType; - const ostring = () => stringType().optional(); - exports.ostring = ostring; - const onumber = () => numberType().optional(); - exports.onumber = onumber; - const oboolean = () => booleanType().optional(); - exports.oboolean = oboolean; - exports.coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), - }; - exports.NEVER = parseUtil_1.INVALID; - } (types)); + var _ZodEnum_cache, _ZodNativeEnum_cache; + class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + } + const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } + }; + function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + var _a, _b; + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; + }; + return { errorMap: customMap, description }; + } + class ZodType { + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: exports.ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: exports.ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: exports.ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } + } + const cuidRegex = /^c[^\s-]{8,}$/i; + const cuid2Regex = /^[0-9a-z]+$/; + const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; + // const uuidRegex = + // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; + const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + const nanoidRegex = /^[a-z0-9_-]{21}$/i; + const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + // from https://stackoverflow.com/a/46181/1550155 + // old version: too slow, didn't support unicode + // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; + //old email regex + // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; + // eslint-disable-next-line + // const emailRegex = + // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; + // const emailRegex = + // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + // const emailRegex = + // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; + const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + // const emailRegex = + // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; + // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression + const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + let emojiRegex; + // faster, simpler, safer + const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; + // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript + const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + // simple + // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; + // no leap year validation + // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; + // with leap year validation + const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; + const dateRegex = new RegExp(`^${dateRegexSource}$`); + function timeRegexSource(args) { + // let regex = `\\d{2}:\\d{2}:\\d{2}`; + let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; + if (args.precision) { + regex = `${regex}\\.\\d{${args.precision}}`; + } + else if (args.precision == null) { + regex = `${regex}(\\.\\d+)?`; + } + return regex; + } + function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); + } + // Adapted from https://stackoverflow.com/a/3143231 + function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); + } + function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; + } + class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a, _b; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); + } + return this._addCheck({ + kind: "time", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 + function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); + } + class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!exports.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || + (ch.kind === "multipleOf" && exports.util.isInteger(ch.value))); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + } + ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: exports.ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: exports.ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + exports.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + } + ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: exports.ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; + class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: exports.ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; + class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: exports.ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; + class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodNull.create = (params) => { + return new ZodNull({ + typeName: exports.ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; + class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodAny.create = (params) => { + return new ZodAny({ + typeName: exports.ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; + class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: exports.ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; + class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + } + ZodNever.create = (params) => { + return new ZodNever({ + typeName: exports.ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; + class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: exports.ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; + class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: exports.ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; + function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } + } + class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = exports.util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") ; + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + exports.util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + exports.util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(exports.util.objectKeys(this.shape)); + } + } + ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } + } + ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: exports.ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + ////////// ////////// + ////////// ZodDiscriminatedUnion ////////// + ////////// ////////// + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return exports.util.objectValues(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } + }; + class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } + } + function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = exports.util.objectKeys(b); + const sharedKeys = exports.util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && + bType === ZodParsedType.date && + +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } + } + class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } + } + ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: exports.ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; + class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } + } + ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: exports.ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; + class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: exports.ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: exports.ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } + } + class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + } + ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: exports.ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; + class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: exports.ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; + class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: exports.ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } + } + class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + } + ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: exports.ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; + class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + } + ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: exports.ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; + function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: exports.ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); + } + class ZodEnum extends ZodType { + constructor() { + super(...arguments); + _ZodEnum_cache.set(this, void 0); + } + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: exports.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!__classPrivateFieldGet(this, _ZodEnum_cache)) { + __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values)); + } + if (!__classPrivateFieldGet(this, _ZodEnum_cache).has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); + } + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); + } + } + _ZodEnum_cache = new WeakMap(); + ZodEnum.create = createZodEnum; + class ZodNativeEnum extends ZodType { + constructor() { + super(...arguments); + _ZodNativeEnum_cache.set(this, void 0); + } + _parse(input) { + const nativeEnumValues = exports.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && + ctx.parsedType !== ZodParsedType.number) { + const expectedValues = exports.util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: exports.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache)) { + __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(exports.util.getValidEnumValues(this._def.values))); + } + if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache).has(input.data)) { + const expectedValues = exports.util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } + } + _ZodNativeEnum_cache = new WeakMap(); + ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; + class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && + ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } + } + ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: exports.ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; + class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } + else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!isValid(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + exports.util.assertNever(effect); + } + } + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: exports.ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; + class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); + }; + class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); + }; + class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } + } + ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); + }; + class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } + } + ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; + class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + } + ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: exports.ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; + const BRAND = Symbol("zod_brand"); + class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } + } + class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: exports.ZodFirstPartyTypeKind.ZodPipeline, + }); + } + } + class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) + ? result.then((data) => freeze(data)) + : freeze(result); + } + unwrap() { + return this._def.innerType; + } + } + ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: exports.ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); + }; + function custom(check, params = {}, + /** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); + } + const late = { + object: ZodObject.lazycreate, + }; + exports.ZodFirstPartyTypeKind = void 0; + (function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; + })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); + const instanceOfType = ( + // const instanceOfType = any>( + cls, params = { + message: `Input not instance of ${cls.name}`, + }) => custom((data) => data instanceof cls, params); + const stringType = ZodString.create; + const numberType = ZodNumber.create; + const nanType = ZodNaN.create; + const bigIntType = ZodBigInt.create; + const booleanType = ZodBoolean.create; + const dateType = ZodDate.create; + const symbolType = ZodSymbol.create; + const undefinedType = ZodUndefined.create; + const nullType = ZodNull.create; + const anyType = ZodAny.create; + const unknownType = ZodUnknown.create; + const neverType = ZodNever.create; + const voidType = ZodVoid.create; + const arrayType = ZodArray.create; + const objectType = ZodObject.create; + const strictObjectType = ZodObject.strictCreate; + const unionType = ZodUnion.create; + const discriminatedUnionType = ZodDiscriminatedUnion.create; + const intersectionType = ZodIntersection.create; + const tupleType = ZodTuple.create; + const recordType = ZodRecord.create; + const mapType = ZodMap.create; + const setType = ZodSet.create; + const functionType = ZodFunction.create; + const lazyType = ZodLazy.create; + const literalType = ZodLiteral.create; + const enumType = ZodEnum.create; + const nativeEnumType = ZodNativeEnum.create; + const promiseType = ZodPromise.create; + const effectsType = ZodEffects.create; + const optionalType = ZodOptional.create; + const nullableType = ZodNullable.create; + const preprocessType = ZodEffects.createWithPreprocess; + const pipelineType = ZodPipeline.create; + const ostring = () => stringType().optional(); + const onumber = () => numberType().optional(); + const oboolean = () => booleanType().optional(); + const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), + }; + const NEVER = INVALID; - (function (exports) { - 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(errors, exports); - __exportStar(parseUtil, exports); - __exportStar(typeAliases, exports); - __exportStar(util, exports); - __exportStar(types, exports); - __exportStar(ZodError$1, exports); - } (external)); + var z = /*#__PURE__*/Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap: setErrorMap, + getErrorMap: getErrorMap, + makeIssue: makeIssue, + EMPTY_PATH: EMPTY_PATH, + addIssueToContext: addIssueToContext, + ParseStatus: ParseStatus, + INVALID: INVALID, + DIRTY: DIRTY, + OK: OK, + isAborted: isAborted, + isDirty: isDirty, + isValid: isValid, + isAsync: isAsync, + get util () { return exports.util; }, + get objectUtil () { return exports.objectUtil; }, + ZodParsedType: ZodParsedType, + getParsedType: getParsedType, + ZodType: ZodType, + datetimeRegex: datetimeRegex, + ZodString: ZodString, + ZodNumber: ZodNumber, + ZodBigInt: ZodBigInt, + ZodBoolean: ZodBoolean, + ZodDate: ZodDate, + ZodSymbol: ZodSymbol, + ZodUndefined: ZodUndefined, + ZodNull: ZodNull, + ZodAny: ZodAny, + ZodUnknown: ZodUnknown, + ZodNever: ZodNever, + ZodVoid: ZodVoid, + ZodArray: ZodArray, + ZodObject: ZodObject, + ZodUnion: ZodUnion, + ZodDiscriminatedUnion: ZodDiscriminatedUnion, + ZodIntersection: ZodIntersection, + ZodTuple: ZodTuple, + ZodRecord: ZodRecord, + ZodMap: ZodMap, + ZodSet: ZodSet, + ZodFunction: ZodFunction, + ZodLazy: ZodLazy, + ZodLiteral: ZodLiteral, + ZodEnum: ZodEnum, + ZodNativeEnum: ZodNativeEnum, + ZodPromise: ZodPromise, + ZodEffects: ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional: ZodOptional, + ZodNullable: ZodNullable, + ZodDefault: ZodDefault, + ZodCatch: ZodCatch, + ZodNaN: ZodNaN, + BRAND: BRAND, + ZodBranded: ZodBranded, + ZodPipeline: ZodPipeline, + ZodReadonly: ZodReadonly, + custom: custom, + Schema: ZodType, + ZodSchema: ZodType, + late: late, + get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; }, + coerce: coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + 'enum': enumType, + 'function': functionType, + 'instanceof': instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + 'null': nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean: oboolean, + onumber: onumber, + optional: optionalType, + ostring: ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + 'undefined': undefinedType, + union: unionType, + unknown: unknownType, + 'void': voidType, + NEVER: NEVER, + ZodIssueCode: ZodIssueCode, + quotelessJson: quotelessJson, + ZodError: ZodError + }); - (function (exports) { - 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 __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - 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 }); - exports.z = void 0; - const z = __importStar(external); - exports.z = z; - __exportStar(external, exports); - exports.default = z; - } (lib)); + try { Object.defineProperty(z, "__" + "esModule", { value: true }); z.default = z; } catch (ex) {} - try { Object.defineProperty(lib, "__" + "esModule", { value: true }); lib.default = lib; } catch (ex) {} + exports.BRAND = BRAND; + exports.DIRTY = DIRTY; + exports.EMPTY_PATH = EMPTY_PATH; + exports.INVALID = INVALID; + exports.NEVER = NEVER; + exports.OK = OK; + exports.ParseStatus = ParseStatus; + exports.Schema = ZodType; + exports.ZodAny = ZodAny; + exports.ZodArray = ZodArray; + exports.ZodBigInt = ZodBigInt; + exports.ZodBoolean = ZodBoolean; + exports.ZodBranded = ZodBranded; + exports.ZodCatch = ZodCatch; + exports.ZodDate = ZodDate; + exports.ZodDefault = ZodDefault; + exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; + exports.ZodEffects = ZodEffects; + exports.ZodEnum = ZodEnum; + exports.ZodError = ZodError; + exports.ZodFunction = ZodFunction; + exports.ZodIntersection = ZodIntersection; + exports.ZodIssueCode = ZodIssueCode; + exports.ZodLazy = ZodLazy; + exports.ZodLiteral = ZodLiteral; + exports.ZodMap = ZodMap; + exports.ZodNaN = ZodNaN; + exports.ZodNativeEnum = ZodNativeEnum; + exports.ZodNever = ZodNever; + exports.ZodNull = ZodNull; + exports.ZodNullable = ZodNullable; + exports.ZodNumber = ZodNumber; + exports.ZodObject = ZodObject; + exports.ZodOptional = ZodOptional; + exports.ZodParsedType = ZodParsedType; + exports.ZodPipeline = ZodPipeline; + exports.ZodPromise = ZodPromise; + exports.ZodReadonly = ZodReadonly; + exports.ZodRecord = ZodRecord; + exports.ZodSchema = ZodType; + exports.ZodSet = ZodSet; + exports.ZodString = ZodString; + exports.ZodSymbol = ZodSymbol; + exports.ZodTransformer = ZodEffects; + exports.ZodTuple = ZodTuple; + exports.ZodType = ZodType; + exports.ZodUndefined = ZodUndefined; + exports.ZodUnion = ZodUnion; + exports.ZodUnknown = ZodUnknown; + exports.ZodVoid = ZodVoid; + exports.addIssueToContext = addIssueToContext; + exports.any = anyType; + exports.array = arrayType; + exports.bigint = bigIntType; + exports.boolean = booleanType; + exports.coerce = coerce; + exports.custom = custom; + exports.date = dateType; + exports.datetimeRegex = datetimeRegex; + exports.default = z; + exports.defaultErrorMap = errorMap; + exports.discriminatedUnion = discriminatedUnionType; + exports.effect = effectsType; + exports.enum = enumType; + exports.function = functionType; + exports.getErrorMap = getErrorMap; + exports.getParsedType = getParsedType; + exports.instanceof = instanceOfType; + exports.intersection = intersectionType; + exports.isAborted = isAborted; + exports.isAsync = isAsync; + exports.isDirty = isDirty; + exports.isValid = isValid; + exports.late = late; + exports.lazy = lazyType; + exports.literal = literalType; + exports.makeIssue = makeIssue; + exports.map = mapType; + exports.nan = nanType; + exports.nativeEnum = nativeEnumType; + exports.never = neverType; + exports.null = nullType; + exports.nullable = nullableType; + exports.number = numberType; + exports.object = objectType; + exports.oboolean = oboolean; + exports.onumber = onumber; + exports.optional = optionalType; + exports.ostring = ostring; + exports.pipeline = pipelineType; + exports.preprocess = preprocessType; + exports.promise = promiseType; + exports.quotelessJson = quotelessJson; + exports.record = recordType; + exports.set = setType; + exports.setErrorMap = setErrorMap; + exports.strictObject = strictObjectType; + exports.string = stringType; + exports.symbol = symbolType; + exports.transformer = effectsType; + exports.tuple = tupleType; + exports.undefined = undefinedType; + exports.union = unionType; + exports.unknown = unknownType; + exports.void = voidType; + exports.z = z; - return lib; + Object.defineProperty(exports, '__esModule', { value: true }); })); diff --git a/packages/ui5-tooling-modules/test/util.test.js b/packages/ui5-tooling-modules/test/util.test.js index 215fdd431..5e0e2bc6b 100644 --- a/packages/ui5-tooling-modules/test/util.test.js +++ b/packages/ui5-tooling-modules/test/util.test.js @@ -584,29 +584,60 @@ test.serial("Verify generation of xml-js", async (t) => { } }); +const webcomponentsContext = { + scope: { + HTMLElement: function () {}, + Element: function () {}, + Node: function () {}, + CSSStyleSheet: function () { + this.replaceSync = function () {}; + }, + customElements: { + get: function () {}, + define: function () {}, + }, + navigator: {}, + document: { + body: { + insertBefore: function () {}, + appendChild: function () {}, + removeChild: function () {}, + }, + createElement: function () { + return { + style: {}, + classList: { + add: function () {}, + }, + setAttribute: function () {}, + }; + }, + querySelector: function () {}, + createTreeWalker: function () {}, + adoptedStyleSheets: [], + }, + location: { + search: "", + }, + getComputedStyle: function () { + return {}; + }, + }, + // running Web Components in the V8 engine causes "TypeError: can't redefine non-configurable property design" + // because the Web Components _generateAccessors doesn't mark the property as configurable + // => so we simply monkey patch the Object.defineProperty call to get rid of this error during the execution + monkeyPatch: "Object.defineProperty = function() { if (arguments[2]) { arguments[2].configurable = true; } return this.apply(undefined, arguments); }.bind(Object.defineProperty);", +}; + test.serial("Verify generation of @ui5/webcomponents/dist/Panel", async (t) => { process.chdir(path.resolve(cwd, "../../showcases/ui5-app")); const env = await setupEnv( ["@ui5/webcomponents/dist/Panel"], - { + Object.assign({}, webcomponentsContext, { hash: t.context.hash, tmpDir: t.context.tmpDir, log: t.context.log, - scope: { - HTMLElement: function () {}, - Element: function () {}, - Node: function () {}, - customElements: { - get: function () {}, - define: function () {}, - }, - navigator: {}, - }, - // running Web Components in the V8 engine causes "TypeError: can't redefine non-configurable property design" - // because the Web Components _generateAccessors doesn't mark the property as configurable - // => so we simply monkey patch the Object.defineProperty call to get rid of this error during the execution - monkeyPatch: "Object.defineProperty = function() { if (arguments[2]) { arguments[2].configurable = true; } return this.apply(undefined, arguments); }.bind(Object.defineProperty);", - }, + }), { pluginOptions: { webcomponents: { @@ -667,25 +698,11 @@ test.serial("Verify generation of @ui5/webcomponents/dist/CheckBox", async (t) = process.chdir(path.resolve(cwd, "../../showcases/ui5-app")); const env = await setupEnv( ["@ui5/webcomponents/dist/CheckBox"], - { + Object.assign({}, webcomponentsContext, { hash: t.context.hash, tmpDir: t.context.tmpDir, log: t.context.log, - scope: { - HTMLElement: function () {}, - Element: function () {}, - Node: function () {}, - customElements: { - get: function () {}, - define: function () {}, - }, - navigator: {}, - }, - // running Web Components in the V8 engine causes "TypeError: can't redefine non-configurable property design" - // because the Web Components _generateAccessors doesn't mark the property as configurable - // => so we simply monkey patch the Object.defineProperty call to get rid of this error during the execution - monkeyPatch: "Object.defineProperty = function() { if (arguments[2]) { arguments[2].configurable = true; } return this.apply(undefined, arguments); }.bind(Object.defineProperty);", - }, + }), { pluginOptions: { webcomponents: { @@ -771,3 +788,23 @@ test.serial("Verify generation of signalr/punycode", async (t) => { t.is(moduleP.code, readSnapFile(moduleP.name, t.context.snapDir)); } }); + +test.serial("Verify generation of @opentelemetry", async (t) => { + process.chdir(path.resolve(cwd, "../../showcases/ui5-app")); + const env = await setupEnv(["@opentelemetry/api", "@opentelemetry/sdk-trace-web"], { + hash: t.context.hash, + tmpDir: t.context.tmpDir, + log: t.context.log, + scope: {}, + }); + const moduleOT_API = await env.getModule("@opentelemetry/api"); + t.true(moduleOT_API.retVal.__esModule); + t.is(typeof moduleOT_API.retVal.trace, "object"); + const moduleOT_SDK = await env.getModule("@opentelemetry/sdk-trace-web"); + t.true(moduleOT_SDK.retVal.__esModule); + t.is(typeof moduleOT_SDK.retVal.WebTracerProvider, "function"); + if (platform() !== "win32") { + t.is(moduleOT_API.code, readSnapFile(moduleOT_API.name, t.context.snapDir)); + t.is(moduleOT_SDK.code, readSnapFile(moduleOT_SDK.name, t.context.snapDir)); + } +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3b4cdc75e..2f0176ee9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -701,6 +701,12 @@ importers: '@octokit/core': specifier: ^4.2.4 version: 4.2.4(encoding@0.1.13) + '@opentelemetry/api': + specifier: ^1.9.0 + version: 1.9.0 + '@opentelemetry/sdk-trace-web': + specifier: ^1.26.0 + version: 1.26.0(@opentelemetry/api@1.9.0) '@stomp/stompjs': specifier: ^7.0.0 version: 7.0.0 @@ -2459,6 +2465,38 @@ packages: '@octokit/types@9.3.2': resolution: {integrity: sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==} + '@opentelemetry/api@1.9.0': + resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/core@1.26.0': + resolution: {integrity: sha512-1iKxXXE8415Cdv0yjG3G6hQnB5eVEsJce3QaawX8SjDn0mAS0ZM8fAbZZJD4ajvhC15cePvosSCut404KrIIvQ==} + engines: {node: '>=14'} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/resources@1.26.0': + resolution: {integrity: sha512-CPNYchBE7MBecCSVy0HKpUISEeJOniWqcHaAHpmasZ3j9o6V3AyBzhRc90jdmemq0HOxDr6ylhUbDhBqqPpeNw==} + engines: {node: '>=14'} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/sdk-trace-base@1.26.0': + resolution: {integrity: sha512-olWQldtvbK4v22ymrKLbIcBi9L2SpMO84sCPY54IVsJhP9fRsxJT194C/AVaAuJzLE30EdhhM1VmvVYR7az+cw==} + engines: {node: '>=14'} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/sdk-trace-web@1.26.0': + resolution: {integrity: sha512-sxeKPcG/gUyxZ8iB8X1MI8/grfSCGgo1n2kxOE73zjVaO9yW/7JuVC3gqUaWRjtZ6VD/V3lo2/ZSwMlm6n2mdg==} + engines: {node: '>=14'} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/semantic-conventions@1.27.0': + resolution: {integrity: sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg==} + engines: {node: '>=14'} + '@pkgjs/parseargs@0.11.0': resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} @@ -11436,6 +11474,35 @@ snapshots: dependencies: '@octokit/openapi-types': 18.1.1 + '@opentelemetry/api@1.9.0': {} + + '@opentelemetry/core@1.26.0(@opentelemetry/api@1.9.0)': + dependencies: + '@opentelemetry/api': 1.9.0 + '@opentelemetry/semantic-conventions': 1.27.0 + + '@opentelemetry/resources@1.26.0(@opentelemetry/api@1.9.0)': + dependencies: + '@opentelemetry/api': 1.9.0 + '@opentelemetry/core': 1.26.0(@opentelemetry/api@1.9.0) + '@opentelemetry/semantic-conventions': 1.27.0 + + '@opentelemetry/sdk-trace-base@1.26.0(@opentelemetry/api@1.9.0)': + dependencies: + '@opentelemetry/api': 1.9.0 + '@opentelemetry/core': 1.26.0(@opentelemetry/api@1.9.0) + '@opentelemetry/resources': 1.26.0(@opentelemetry/api@1.9.0) + '@opentelemetry/semantic-conventions': 1.27.0 + + '@opentelemetry/sdk-trace-web@1.26.0(@opentelemetry/api@1.9.0)': + dependencies: + '@opentelemetry/api': 1.9.0 + '@opentelemetry/core': 1.26.0(@opentelemetry/api@1.9.0) + '@opentelemetry/sdk-trace-base': 1.26.0(@opentelemetry/api@1.9.0) + '@opentelemetry/semantic-conventions': 1.27.0 + + '@opentelemetry/semantic-conventions@1.27.0': {} + '@pkgjs/parseargs@0.11.0': optional: true diff --git a/showcases/ui5-app/package.json b/showcases/ui5-app/package.json index 3b159c575..63e3691e9 100644 --- a/showcases/ui5-app/package.json +++ b/showcases/ui5-app/package.json @@ -41,6 +41,8 @@ "dependencies": { "@js-temporal/polyfill": "^0.4.4", "@octokit/core": "^4.2.4", + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/sdk-trace-web": "^1.26.0", "@stomp/stompjs": "^7.0.0", "@supabase/supabase-js": "^2.45.3", "@ui5/webcomponents": "^2.1.2", diff --git a/showcases/ui5-app/webapp/controller/Thirdparty.controller.js b/showcases/ui5-app/webapp/controller/Thirdparty.controller.js index 3e16548a7..5bde91c74 100644 --- a/showcases/ui5-app/webapp/controller/Thirdparty.controller.js +++ b/showcases/ui5-app/webapp/controller/Thirdparty.controller.js @@ -21,8 +21,33 @@ sap.ui.define( "firebase/firestore/lite", "signalr", "mypackage", + "@opentelemetry/api", + "@opentelemetry/sdk-trace-web", ], - (Controller, MessageToast, jQuery, xlsx, cmis, supabase, octokit, axios, temporal, stompjs, react, reactdom, zod, pdfMake, pdfFonts, xmljs, firebase, firestore, signalr, mypackage) => { + ( + Controller, + MessageToast, + jQuery, + xlsx, + cmis, + supabase, + octokit, + axios, + temporal, + stompjs, + react, + reactdom, + zod, + pdfMake, + pdfFonts, + xmljs, + firebase, + firestore, + signalr, + mypackage, + otAPI, + otSDK, + ) => { "use strict"; console.log("[3rdParty] xlsx", xlsx); @@ -54,6 +79,9 @@ sap.ui.define( console.log("[3rdParty] signalr", signalr, jQuery.connection.hub); console.log("[3rdParty] mypackage", mypackage); + console.log("[3rdParty] @opentelemetry/api", otAPI); + console.log("[3rdParty] @opentelemetry/sdk-trace-web", otSDK); + return Controller.extend("ui5.ecosystem.demo.app.controller.Thirdparty", { onInit() { // https://www.npmjs.com/package/xlsx @@ -74,5 +102,5 @@ sap.ui.define( this.byId("webcBtn").setText(event.getSource().getValue()); }, }); - } + }, );