From 6e33a97227f8e78aceada392da7d9d5f977099ec Mon Sep 17 00:00:00 2001 From: Jan Matuszewski Date: Fri, 20 Aug 2021 12:05:29 +0200 Subject: [PATCH] feat: send each doc as one record to Algolia (#10) * Send each Doc as one record to Algolia Earlier each doc were split by headings and sent as X records to Algolia causing search returning the same document multiple times. --- .eslintignore | 2 + dist/index.js | 61974 +++++++++++++++++++++++++++++--------------- dist/index.js.map | 2 +- index.mjs | 54 +- 4 files changed, 41516 insertions(+), 20516 deletions(-) create mode 100644 .eslintignore diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..b947077 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ diff --git a/dist/index.js b/dist/index.js index f1f2bca..882d93c 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,5123 +1,5556 @@ -require('./sourcemap-register.js');module.exports = -/******/ (() => { // webpackBootstrap -/******/ var __webpack_modules__ = ({ - -/***/ 4501: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var core = __webpack_require__(2186); -// EXTERNAL MODULE: ./node_modules/algoliasearch/index.js -var algoliasearch = __webpack_require__(930); -// EXTERNAL MODULE: ./node_modules/unified/index.js -var unified = __webpack_require__(5075); -// EXTERNAL MODULE: ./node_modules/remark-parse/index.js -var remark_parse = __webpack_require__(4859); -// EXTERNAL MODULE: ./node_modules/remark-rehype/index.js -var remark_rehype = __webpack_require__(4892); -// EXTERNAL MODULE: ./node_modules/rehype-raw/index.js -var rehype_raw = __webpack_require__(9830); -// EXTERNAL MODULE: ./node_modules/mdast-util-to-string/index.js -var mdast_util_to_string = __webpack_require__(5789); -// EXTERNAL MODULE: ./node_modules/github-slugger/index.js -var github_slugger = __webpack_require__(237); -// EXTERNAL MODULE: ./node_modules/md5/md5.js -var md5 = __webpack_require__(1711); -// CONCATENATED MODULE: ./lib/docs/utils.mjs -/** - * Copyright © 2020 Vercel Inc. All rights reserved. - * Forked from: vercel/nextjs-website - */ - -// Handle optional catch all route for `/docs` -function getDocsSlug(slug) { - if (slug && slug.length) { - return slug - } else { - return 'quickstart' - } -} - -function getSlug(params) { - // Handle optional catch all route for `/docs` - const slug = getDocsSlug(params.slug) - if (slug[0] === 'tag') { - return { - tag: slug[1], - slug: `/docs/${getDocsSlug(slug.slice(2)).join('/')}` - } - } - - return { slug: `/docs/${slug.join('/')}` } -} - -function removeFromLast(path, key) { - const i = path.lastIndexOf(key) - return i === -1 ? path : path.substring(0, i) -} +require('./sourcemap-register.js') +module.exports = /******/ (() => { + // webpackBootstrap + /******/ var __webpack_modules__ = { + /***/ 4501: /***/ ( + __unused_webpack___webpack_module__, + __webpack_exports__, + __webpack_require__ + ) => { + 'use strict' + // ESM COMPAT FLAG + __webpack_require__.r(__webpack_exports__) + + // EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js + var core = __webpack_require__(2186) + // EXTERNAL MODULE: ./node_modules/algoliasearch/index.js + var algoliasearch = __webpack_require__(930) + // EXTERNAL MODULE: ./node_modules/unified/index.js + var unified = __webpack_require__(5075) + // EXTERNAL MODULE: ./node_modules/remark-parse/index.js + var remark_parse = __webpack_require__(4859) + // EXTERNAL MODULE: ./node_modules/remark-rehype/index.js + var remark_rehype = __webpack_require__(4892) + // EXTERNAL MODULE: ./node_modules/rehype-raw/index.js + var rehype_raw = __webpack_require__(9830) + // EXTERNAL MODULE: ./node_modules/mdast-util-to-string/index.js + var mdast_util_to_string = __webpack_require__(5789) + // EXTERNAL MODULE: ./node_modules/github-slugger/index.js + var github_slugger = __webpack_require__(237) + // EXTERNAL MODULE: ./node_modules/md5/md5.js + var md5 = __webpack_require__(1711) + // CONCATENATED MODULE: ./lib/docs/utils.mjs + /** + * Copyright © 2020 Vercel Inc. All rights reserved. + * Forked from: vercel/nextjs-website + */ + + // Handle optional catch all route for `/docs` + function getDocsSlug(slug) { + if (slug && slug.length) { + return slug + } else { + return 'quickstart' + } + } -function addTagToSlug(slug, tag) { - return tag ? slug.replace('/docs', `/docs/tag/${tag}`) : slug -} + function getSlug(params) { + // Handle optional catch all route for `/docs` + const slug = getDocsSlug(params.slug) + if (slug[0] === 'tag') { + return { + tag: slug[1], + slug: `/docs/${getDocsSlug(slug.slice(2)).join('/')}` + } + } -// EXTERNAL MODULE: external "fs" -var external_fs_ = __webpack_require__(5747); -// EXTERNAL MODULE: external "path" -var external_path_ = __webpack_require__(5622); -// CONCATENATED MODULE: ./lib/docs/page.mjs + return { slug: `/docs/${slug.join('/')}` } + } + function removeFromLast(path, key) { + const i = path.lastIndexOf(key) + return i === -1 ? path : path.substring(0, i) + } + function addTagToSlug(slug, tag) { + return tag ? slug.replace('/docs', `/docs/tag/${tag}`) : slug + } -function fetchDocsManifest() { - const filePath = external_path_.join(process.cwd(), 'docs') - const contents = external_fs_.readFileSync(`${filePath}/manifest.json`, 'utf8') - const jp = JSON.parse(contents) - return jp -} + // EXTERNAL MODULE: external "fs" + var external_fs_ = __webpack_require__(5747) + // EXTERNAL MODULE: external "path" + var external_path_ = __webpack_require__(5622) + // CONCATENATED MODULE: ./lib/docs/page.mjs + + function fetchDocsManifest() { + const filePath = __webpack_require__.ab + 'docs' + const contents = external_fs_.readFileSync( + __webpack_require__.ab + 'manifest.json', + 'utf8' + ) + const jp = JSON.parse(contents) + return jp + } -function getFile(file) { - const filePath = external_path_.join(process.cwd(), file) - return external_fs_.readFileSync(`${filePath}`, 'utf8') -} + function getFile(file) { + const filePath = external_path_.join(process.cwd(), file) + return external_fs_.readFileSync(`${filePath}`, 'utf8') + } -// CONCATENATED MODULE: ./index.mjs + // CONCATENATED MODULE: ./index.mjs + const HEADINGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] + const CONTAINERS = ['ul', 'ol', 'details'] + const CONTENT = ['p', 'blockquote', 'li'] + const processor = unified() + .use(remark_parse) + .use(remark_rehype, { allowDangerousHtml: true }) + .use(rehype_raw) + .use(toTree) + function toTree() { + // A compiler is required, and we only need the AST + this.Compiler = (tree) => tree + } + function flattenRoutes(carry, { path, routes }) { + if (path) { + carry.push(path) + } else if (routes) { + routes.forEach((route) => { + flattenRoutes(carry, route) + }) + } + return carry + } + function getText(node) { + return mdast_util_to_string(node).replace(/\xA0/g, ' ') + } + async function addRecords(filePath) { + const md = await getFile(filePath) + const tree = await processor.process(md) + const { result } = tree + const slugger = new github_slugger() + const records = [] + let record = { + content: '', + sections: [] + } + const addSection = (node) => { + const text = getText(node) + record.sections.push({ + name: text, + anchor: slugger.slug(text), + subsections: [], + content: '' + }) + } + const addSubSection = (name) => { + if (record.sections.length !== 0) { + record.sections[record.sections.length - 1].subsections.push(name) + } + } + const addContent = (text) => { + if (record.sections.length === 0) { + record.content += text + } else { + record.sections[record.sections.length - 1].content += text + } + } + const handleHeading = (node) => { + const value = getText(node) + switch (node.tagName) { + case 'h1': + record.title = value + record.anchor = slugger.slug(value) + break + case 'h2': + addSection(node) + break + case 'h3': + addSubSection(value) + break + case 'h4': + case 'h5': + case 'h6': + addSubSection(value) + break + default: + throw new Error(`Unhandled node: ${node.tagName}`) + } + } + const addRecord = () => { + const path = removeFromLast(filePath, '.') + const objectID = `${path}-${md5(record.anchor)}` + records.push({ ...record, path, objectID }) + } + const handleNode = (node, parent) => { + if (node.type === 'element') { + if (node.tagName === 'summary' && parent.tagName === 'details') { + record.summary = getText(node) + return + } -const HEADINGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] -const CONTAINERS = ['ul', 'ol', 'details'] -const CONTENT = ['p', 'blockquote', 'li'] + if (CONTENT.includes(node.tagName)) { + let text = getText(node) + addContent(text) + return + } -const processor = unified() - .use(remark_parse) - .use(remark_rehype, { allowDangerousHtml: true }) - .use(rehype_raw) - .use(toTree) + if (HEADINGS.includes(node.tagName)) { + handleHeading(node) + return + } -function toTree() { - // A compiler is required, and we only need the AST - this.Compiler = (tree) => tree -} + if (CONTAINERS.includes(node.tagName)) { + if (node.children) { + node.children.forEach((n) => handleNode(n, node)) -function flattenRoutes(carry, { path, routes }) { - if (path) { - carry.push(path) - } else if (routes) { - routes.forEach((route) => { - flattenRoutes(carry, route) - }) - } - return carry -} + if (node.tagName === 'details') { + delete record.summary + } + } + } + } + } -function getText(node) { - return mdast_util_to_string(node).replace(/\xA0/g, ' ') -} + result.children.forEach(handleNode) + addRecord() -async function addRecords(filePath) { - const md = await getFile(filePath) - const tree = await processor.process(md) + return records + } - const { result } = tree - const slugger = new github_slugger() - const records = [] + async function indexDocs() { + const client = algoliasearch( + core.getInput('algoliaId'), + core.getInput('algoliaKey') + ) + // Init the docs index, this will throw if the index doesn't exist + const index = await client.initIndex(core.getInput('algoliaIndex')) + const manifest = fetchDocsManifest() + const files = manifest.routes.reduce(flattenRoutes, []) + const recordsByFile = await Promise.all( + files.map((filePath) => addRecords(filePath)) + ) + // Group all records into a single array + const objects = recordsByFile.reduce((records, record) => { + records.push(...record) + return records + }, []) - let record = {} - let position = 0 + // Init a temporal index which will receive the objects + const tmpIndex = await client.initIndex('docs_tmp') - const handleHeading = (node) => { - const value = getText(node) + // Copy the settings from the main index to the temporal index + await client.copySettings(index.indexName, tmpIndex.indexName) - switch (node.tagName) { - case 'h1': - record = { title: value } - break - case 'h2': - record.section = value - record.anchor = slugger.slug(value) - delete record.subSection - break - case 'h3': - record.subSection = value - record.anchor = slugger.slug(value) - break - case 'h4': - case 'h5': - case 'h6': - record.anchor = slugger.slug(value) - addRecord(node) - break - default: - throw new Error(`Unhandled node: ${node.tagName}`) - } - } - const addRecord = (node) => { - const content = getText(node) - const path = removeFromLast(filePath, '.') - const objectID = `${path}-${md5(content)}` + while (objects.length) { + const { taskIDs } = await tmpIndex.saveObjects( + objects.splice(0, 1000) + ) - records.push({ ...record, content, path, objectID, position }) - position += 1 - } - const handleNode = (node, parent) => { - if (node.type === 'element') { - if (node.tagName === 'summary' && parent.tagName === 'details') { - record.summary = getText(node) - return - } + while (taskIDs.length) { + await tmpIndex.waitTask(taskIDs.shift()) + } + } - if (CONTENT.includes(node.tagName)) { - addRecord(node) - return + // Move the temporal index to the docs index, this will rename the temporal index + // so we don't have to remove it + await client.moveIndex(tmpIndex.indexName, index.indexName) } - if (HEADINGS.includes(node.tagName)) { - handleHeading(node) - return - } + indexDocs() - if (CONTAINERS.includes(node.tagName)) { - if (node.children) { - node.children.forEach((n) => handleNode(n, node)) + /***/ + }, - if (node.tagName === 'details') { - delete record.summary - } + /***/ 7351: /***/ function ( + __unused_webpack_module, + exports, + __webpack_require__ + ) { + 'use strict' + + var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod + var result = {} + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k] + result['default'] = mod + return result } + Object.defineProperty(exports, '__esModule', { value: true }) + const os = __importStar(__webpack_require__(2087)) + const utils_1 = __webpack_require__(5278) + /** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ + function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message) + process.stdout.write(cmd.toString() + os.EOL) } - } - } - - result.children.forEach(handleNode) - - return records -} - -async function indexDocs() { - const client = algoliasearch( - core.getInput('algoliaId'), - core.getInput('algoliaKey') - ) - // Init the docs index, this will throw if the index doesn't exist - const index = await client.initIndex(core.getInput('algoliaIndex')) - const manifest = fetchDocsManifest() - const files = manifest.routes.reduce(flattenRoutes, []) - const recordsByFile = await Promise.all( - files.map((filePath) => addRecords(filePath)) - ) - // Group all records into a single array - const objects = recordsByFile.reduce((records, record) => { - records.push(...record) - return records - }, []) - - // Init a temporal index which will receive the objects - const tmpIndex = await client.initIndex('docs_tmp') - - // Copy the settings from the main index to the temporal index - await client.copySettings(index.indexName, tmpIndex.indexName) - - while (objects.length) { - const { taskIDs } = await tmpIndex.saveObjects(objects.splice(0, 1000)) - - while (taskIDs.length) { - await tmpIndex.waitTask(taskIDs.shift()) - } - } - - // Move the temporal index to the docs index, this will rename the temporal index - // so we don't have to remove it - await client.moveIndex(tmpIndex.indexName, index.indexName) -} - -indexDocs() - - -/***/ }), - -/***/ 7351: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const os = __importStar(__webpack_require__(2087)); -const utils_1 = __webpack_require__(5278); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; + exports.issueCommand = issueCommand + function issue(name, message = '') { + issueCommand(name, {}, message) + } + exports.issue = issue + const CMD_STRING = '::' + class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command' + } + this.command = command + this.properties = properties + this.message = message + } + toString() { + let cmdStr = CMD_STRING + this.command + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' ' + let first = true for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key] + if (val) { + if (first) { + first = false + } else { + cmdStr += ',' + } + cmdStr += `${key}=${escapeProperty(val)}` } + } } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}` + return cmdStr } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map - -/***/ }), - -/***/ 2186: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __webpack_require__(7351); -const file_command_1 = __webpack_require__(717); -const utils_1 = __webpack_require__(5278); -const os = __importStar(__webpack_require__(2087)); -const path = __importStar(__webpack_require__(5622)); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - const delimiter = '_GitHubActionsFileCommandDelimeter_'; - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); - } -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. The value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - command_1.issueCommand('set-output', { name }, value); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds an warning issue - * @param message warning issue message. Errors will be converted to string via toString() - */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 717: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -// For internal use, subject to change. -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__webpack_require__(5747)); -const os = __importStar(__webpack_require__(2087)); -const utils_1 = __webpack_require__(5278); -function issueCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueCommand = issueCommand; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 5278: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 3818: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -// @todo Add logger on options to debug when caches go wrong. -function createFallbackableCache(options) { - const caches = [...options.caches]; - const current = caches.shift(); // eslint-disable-line functional/immutable-data - if (current === undefined) { - return createNullCache(); - } - return { - get(key, defaultValue, events = { - miss: () => Promise.resolve(), - }) { - return current.get(key, defaultValue, events).catch(() => { - return createFallbackableCache({ caches }).get(key, defaultValue, events); - }); - }, - set(key, value) { - return current.set(key, value).catch(() => { - return createFallbackableCache({ caches }).set(key, value); - }); - }, - delete(key) { - return current.delete(key).catch(() => { - return createFallbackableCache({ caches }).delete(key); - }); - }, - clear() { - return current.clear().catch(() => { - return createFallbackableCache({ caches }).clear(); - }); - }, - }; -} - -function createNullCache() { - return { - get(_key, defaultValue, events = { - miss: () => Promise.resolve(), - }) { - const value = defaultValue(); - return value - .then(result => Promise.all([result, events.miss(result)])) - .then(([result]) => result); - }, - set(_key, value) { - return Promise.resolve(value); - }, - delete(_key) { - return Promise.resolve(); - }, - clear() { - return Promise.resolve(); - }, - }; -} - -exports.createFallbackableCache = createFallbackableCache; -exports.createNullCache = createNullCache; - - -/***/ }), - -/***/ 8848: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(3818); - - -/***/ }), - -/***/ 2703: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function createInMemoryCache(options = { serializable: true }) { - // eslint-disable-next-line functional/no-let - let cache = {}; - return { - get(key, defaultValue, events = { - miss: () => Promise.resolve(), - }) { - const keyAsString = JSON.stringify(key); - if (keyAsString in cache) { - return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); - } - const promise = defaultValue(); - const miss = (events && events.miss) || (() => Promise.resolve()); - return promise.then((value) => miss(value)).then(() => promise); - }, - set(key, value) { - // eslint-disable-next-line functional/immutable-data - cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; - return Promise.resolve(value); - }, - delete(key) { - // eslint-disable-next-line functional/immutable-data - delete cache[JSON.stringify(key)]; - return Promise.resolve(); - }, - clear() { - cache = {}; - return Promise.resolve(); - }, - }; -} - -exports.createInMemoryCache = createInMemoryCache; - - -/***/ }), - -/***/ 8069: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(2703); - - -/***/ }), - -/***/ 6675: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var clientCommon = __webpack_require__(1905); -var transporter = __webpack_require__(2424); -var requesterCommon = __webpack_require__(6373); - -const createAnalyticsClient = options => { - const region = options.region || 'us'; - const auth = clientCommon.createAuth(clientCommon.AuthMode.WithinHeaders, options.appId, options.apiKey); - const transporter$1 = transporter.createTransporter({ - hosts: [{ url: `analytics.${region}.algolia.com` }], - ...options, - headers: { - ...auth.headers(), - ...{ 'content-type': 'application/json' }, - ...options.headers, - }, - queryParameters: { - ...auth.queryParameters(), - ...options.queryParameters, - }, - }); - const appId = options.appId; - return clientCommon.addMethods({ appId, transporter: transporter$1 }, options.methods); -}; - -const addABTest = (base) => { - return (abTest, requestOptions) => { - return base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: '2/abtests', - data: abTest, - }, requestOptions); - }; -}; - -const deleteABTest = (base) => { - return (abTestID, requestOptions) => { - return base.transporter.write({ - method: requesterCommon.MethodEnum.Delete, - path: clientCommon.encode('2/abtests/%s', abTestID), - }, requestOptions); - }; -}; - -const getABTest = (base) => { - return (abTestID, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('2/abtests/%s', abTestID), - }, requestOptions); - }; -}; - -const getABTests = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '2/abtests', - }, requestOptions); - }; -}; - -const stopABTest = (base) => { - return (abTestID, requestOptions) => { - return base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('2/abtests/%s/stop', abTestID), - }, requestOptions); - }; -}; - -exports.addABTest = addABTest; -exports.createAnalyticsClient = createAnalyticsClient; -exports.deleteABTest = deleteABTest; -exports.getABTest = getABTest; -exports.getABTests = getABTests; -exports.stopABTest = stopABTest; - - -/***/ }), - -/***/ 7538: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(6675); - - -/***/ }), - -/***/ 5526: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function createAuth(authMode, appId, apiKey) { - const credentials = { - 'x-algolia-api-key': apiKey, - 'x-algolia-application-id': appId, - }; - return { - headers() { - return authMode === AuthMode.WithinHeaders ? credentials : {}; - }, - queryParameters() { - return authMode === AuthMode.WithinQueryParameters ? credentials : {}; - }, - }; -} - -function createRetryablePromise(callback) { - let retriesCount = 0; // eslint-disable-line functional/no-let - const retry = () => { - retriesCount++; - return new Promise((resolve) => { - setTimeout(() => { - resolve(callback(retry)); - }, Math.min(100 * retriesCount, 1000)); - }); - }; - return callback(retry); -} - -function createWaitablePromise(promise, wait = (_response, _requestOptions) => { - return Promise.resolve(); -}) { - // eslint-disable-next-line functional/immutable-data - return Object.assign(promise, { - wait(requestOptions) { - return createWaitablePromise(promise - .then(response => Promise.all([wait(response, requestOptions), response])) - .then(promiseResults => promiseResults[1])); - }, - }); -} - -// eslint-disable-next-line functional/prefer-readonly-type -function shuffle(array) { - let c = array.length - 1; // eslint-disable-line functional/no-let - // eslint-disable-next-line functional/no-loop-statement - for (c; c > 0; c--) { - const b = Math.floor(Math.random() * (c + 1)); - const a = array[c]; - array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign - array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign - } - return array; -} -function addMethods(base, methods) { - if (!methods) { - return base; - } - Object.keys(methods).forEach(key => { - // eslint-disable-next-line functional/immutable-data, no-param-reassign - base[key] = methods[key](base); - }); - return base; -} -function encode(format, ...args) { - // eslint-disable-next-line functional/no-let - let i = 0; - return format.replace(/%s/g, () => encodeURIComponent(args[i++])); -} - -const version = '4.8.3'; - -const destroy = (base) => { - return () => { - return base.transporter.requester.destroy(); - }; -}; - -const AuthMode = { - /** - * If auth credentials should be in query parameters. - */ - WithinQueryParameters: 0, - /** - * If auth credentials should be in headers. - */ - WithinHeaders: 1, -}; - -exports.AuthMode = AuthMode; -exports.addMethods = addMethods; -exports.createAuth = createAuth; -exports.createRetryablePromise = createRetryablePromise; -exports.createWaitablePromise = createWaitablePromise; -exports.destroy = destroy; -exports.encode = encode; -exports.shuffle = shuffle; -exports.version = version; - - -/***/ }), - -/***/ 1905: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(5526); - - -/***/ }), - -/***/ 1557: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var clientCommon = __webpack_require__(1905); -var transporter = __webpack_require__(2424); -var requesterCommon = __webpack_require__(6373); - -const createRecommendationClient = options => { - const region = options.region || 'us'; - const auth = clientCommon.createAuth(clientCommon.AuthMode.WithinHeaders, options.appId, options.apiKey); - const transporter$1 = transporter.createTransporter({ - hosts: [{ url: `recommendation.${region}.algolia.com` }], - ...options, - headers: { - ...auth.headers(), - ...{ 'content-type': 'application/json' }, - ...options.headers, - }, - queryParameters: { - ...auth.queryParameters(), - ...options.queryParameters, - }, - }); - return clientCommon.addMethods({ appId: options.appId, transporter: transporter$1 }, options.methods); -}; - -const getPersonalizationStrategy = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/strategies/personalization', - }, requestOptions); - }; -}; - -const setPersonalizationStrategy = (base) => { - return (personalizationStrategy, requestOptions) => { - return base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: '1/strategies/personalization', - data: personalizationStrategy, - }, requestOptions); - }; -}; - -exports.createRecommendationClient = createRecommendationClient; -exports.getPersonalizationStrategy = getPersonalizationStrategy; -exports.setPersonalizationStrategy = setPersonalizationStrategy; - - -/***/ }), - -/***/ 31: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(1557); - - -/***/ }), - -/***/ 102: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var clientCommon = __webpack_require__(1905); -var transporter = __webpack_require__(2424); -var requesterCommon = __webpack_require__(6373); -var crypto = __webpack_require__(6417); - -function createBrowsablePromise(options) { - const browse = (data) => { - return options.request(data).then(response => { - /** - * First we send to the developer the - * batch retrieved from the API. - */ - if (options.batch !== undefined) { - options.batch(response.hits); - } - /** - * Then, we ask to the browse concrete implementation - * if we should stop browsing. As example, the `browseObjects` - * method will stop if the cursor is not present on the response. - */ - if (options.shouldStop(response)) { - return undefined; - } - /** - * Finally, if the response contains a cursor, we browse to the next - * batch using that same cursor. Otherwise, we just use the traditional - * browsing using the page element. - */ - if (response.cursor) { - return browse({ - cursor: response.cursor, - }); - } - return browse({ - page: (data.page || 0) + 1, - }); - }); - }; - return browse({}); -} - -const createSearchClient = options => { - const appId = options.appId; - const auth = clientCommon.createAuth(options.authMode !== undefined ? options.authMode : clientCommon.AuthMode.WithinHeaders, appId, options.apiKey); - const transporter$1 = transporter.createTransporter({ - hosts: [ - { url: `${appId}-dsn.algolia.net`, accept: transporter.CallEnum.Read }, - { url: `${appId}.algolia.net`, accept: transporter.CallEnum.Write }, - ].concat(clientCommon.shuffle([ - { url: `${appId}-1.algolianet.com` }, - { url: `${appId}-2.algolianet.com` }, - { url: `${appId}-3.algolianet.com` }, - ])), - ...options, - headers: { - ...auth.headers(), - ...{ 'content-type': 'application/x-www-form-urlencoded' }, - ...options.headers, - }, - queryParameters: { - ...auth.queryParameters(), - ...options.queryParameters, - }, - }); - const base = { - transporter: transporter$1, - appId, - addAlgoliaAgent(segment, version) { - transporter$1.userAgent.add({ segment, version }); - }, - clearCache() { - return Promise.all([ - transporter$1.requestsCache.clear(), - transporter$1.responsesCache.clear(), - ]).then(() => undefined); - }, - }; - return clientCommon.addMethods(base, options.methods); -}; - -function createMissingObjectIDError() { - return { - name: 'MissingObjectIDError', - message: 'All objects must have an unique objectID ' + - '(like a primary key) to be valid. ' + - 'Algolia is also able to generate objectIDs ' + - "automatically but *it's not recommended*. " + - "To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option.", - }; -} - -function createObjectNotFoundError() { - return { - name: 'ObjectNotFoundError', - message: 'Object not found.', - }; -} - -function createValidUntilNotFoundError() { - return { - name: 'ValidUntilNotFoundError', - message: 'ValidUntil not found in given secured api key.', - }; -} - -const addApiKey = (base) => { - return (acl, requestOptions) => { - const { queryParameters, ...options } = requestOptions || {}; - const data = { - acl, - ...(queryParameters !== undefined ? { queryParameters } : {}), - }; - const wait = (response, waitRequestOptions) => { - return clientCommon.createRetryablePromise(retry => { - return getApiKey(base)(response.key, waitRequestOptions).catch((apiError) => { - if (apiError.status !== 404) { - throw apiError; - } - return retry(); - }); - }); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: '1/keys', - data, - }, options), wait); - }; -}; - -const assignUserID = (base) => { - return (userID, clusterName, requestOptions) => { - const mappedRequestOptions = transporter.createMappedRequestOptions(requestOptions); - // eslint-disable-next-line functional/immutable-data - mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; - return base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: '1/clusters/mapping', - data: { cluster: clusterName }, - }, mappedRequestOptions); - }; -}; - -const assignUserIDs = (base) => { - return (userIDs, clusterName, requestOptions) => { - return base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: '1/clusters/mapping/batch', - data: { - users: userIDs, - cluster: clusterName, - }, - }, requestOptions); - }; -}; - -const copyIndex = (base) => { - return (from, to, requestOptions) => { - const wait = (response, waitRequestOptions) => { - return initIndex(base)(from, { - methods: { waitTask }, - }).waitTask(response.taskID, waitRequestOptions); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/operation', from), - data: { - operation: 'copy', - destination: to, - }, - }, requestOptions), wait); - }; -}; - -const copyRules = (base) => { - return (from, to, requestOptions) => { - return copyIndex(base)(from, to, { - ...requestOptions, - scope: [ScopeEnum.Rules], - }); - }; -}; - -const copySettings = (base) => { - return (from, to, requestOptions) => { - return copyIndex(base)(from, to, { - ...requestOptions, - scope: [ScopeEnum.Settings], - }); - }; -}; - -const copySynonyms = (base) => { - return (from, to, requestOptions) => { - return copyIndex(base)(from, to, { - ...requestOptions, - scope: [ScopeEnum.Synonyms], - }); - }; -}; - -const deleteApiKey = (base) => { - return (apiKey, requestOptions) => { - const wait = (_, waitRequestOptions) => { - return clientCommon.createRetryablePromise(retry => { - return getApiKey(base)(apiKey, waitRequestOptions) - .then(retry) - .catch((apiError) => { - if (apiError.status !== 404) { - throw apiError; - } - }); - }); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Delete, - path: clientCommon.encode('1/keys/%s', apiKey), - }, requestOptions), wait); - }; -}; - -const generateSecuredApiKey = () => { - return (parentApiKey, restrictions) => { - const queryParameters = transporter.serializeQueryParameters(restrictions); - const securedKey = crypto.createHmac('sha256', parentApiKey) - .update(queryParameters) - .digest('hex'); - return Buffer.from(securedKey + queryParameters).toString('base64'); - }; -}; - -const getApiKey = (base) => { - return (apiKey, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('1/keys/%s', apiKey), - }, requestOptions); - }; -}; - -const getLogs = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/logs', - }, requestOptions); - }; -}; - -const getSecuredApiKeyRemainingValidity = () => { - return (securedApiKey) => { - const decodedString = Buffer.from(securedApiKey, 'base64').toString('ascii'); - const regex = /validUntil=(\d+)/; - const match = decodedString.match(regex); - if (match === null) { - throw createValidUntilNotFoundError(); - } - return parseInt(match[1], 10) - Math.round(new Date().getTime() / 1000); - }; -}; - -const getTopUserIDs = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/clusters/mapping/top', - }, requestOptions); - }; -}; - -const getUserID = (base) => { - return (userID, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('1/clusters/mapping/%s', userID), - }, requestOptions); - }; -}; - -const hasPendingMappings = (base) => { - return (requestOptions) => { - const { retrieveMappings, ...options } = requestOptions || {}; - if (retrieveMappings === true) { - // eslint-disable-next-line functional/immutable-data - options.getClusters = true; - } - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/clusters/mapping/pending', - }, options); - }; -}; - -const initIndex = (base) => { - return (indexName, options = {}) => { - const searchIndex = { - transporter: base.transporter, - appId: base.appId, - indexName, - }; - return clientCommon.addMethods(searchIndex, options.methods); - }; -}; - -const listApiKeys = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/keys', - }, requestOptions); - }; -}; - -const listClusters = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/clusters', - }, requestOptions); - }; -}; - -const listIndices = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/indexes', - }, requestOptions); - }; -}; - -const listUserIDs = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: '1/clusters/mapping', - }, requestOptions); - }; -}; - -const moveIndex = (base) => { - return (from, to, requestOptions) => { - const wait = (response, waitRequestOptions) => { - return initIndex(base)(from, { - methods: { waitTask }, - }).waitTask(response.taskID, waitRequestOptions); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/operation', from), - data: { - operation: 'move', - destination: to, - }, - }, requestOptions), wait); - }; -}; - -const multipleBatch = (base) => { - return (requests, requestOptions) => { - const wait = (response, waitRequestOptions) => { - return Promise.all(Object.keys(response.taskID).map(indexName => { - return initIndex(base)(indexName, { - methods: { waitTask }, - }).waitTask(response.taskID[indexName], waitRequestOptions); - })); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: '1/indexes/*/batch', - data: { - requests, - }, - }, requestOptions), wait); - }; -}; - -const multipleGetObjects = (base) => { - return (requests, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: '1/indexes/*/objects', - data: { - requests, - }, - }, requestOptions); - }; -}; - -const multipleQueries = (base) => { - return (queries, requestOptions) => { - const requests = queries.map(query => { - return { - ...query, - params: transporter.serializeQueryParameters(query.params || {}), - }; - }); - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: '1/indexes/*/queries', - data: { - requests, - }, - cacheable: true, - }, requestOptions); - }; -}; - -const multipleSearchForFacetValues = (base) => { - return (queries, requestOptions) => { - return Promise.all(queries.map(query => { - const { facetName, facetQuery, ...params } = query.params; - return initIndex(base)(query.indexName, { - methods: { searchForFacetValues }, - }).searchForFacetValues(facetName, facetQuery, { - ...requestOptions, - ...params, - }); - })); - }; -}; - -const removeUserID = (base) => { - return (userID, requestOptions) => { - const mappedRequestOptions = transporter.createMappedRequestOptions(requestOptions); - // eslint-disable-next-line functional/immutable-data - mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID; - return base.transporter.write({ - method: requesterCommon.MethodEnum.Delete, - path: '1/clusters/mapping', - }, mappedRequestOptions); - }; -}; - -const restoreApiKey = (base) => { - return (apiKey, requestOptions) => { - const wait = (_, waitRequestOptions) => { - return clientCommon.createRetryablePromise(retry => { - return getApiKey(base)(apiKey, waitRequestOptions).catch((apiError) => { - if (apiError.status !== 404) { - throw apiError; - } - return retry(); - }); - }); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/keys/%s/restore', apiKey), - }, requestOptions), wait); - }; -}; - -const searchUserIDs = (base) => { - return (query, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: '1/clusters/mapping/search', - data: { - query, - }, - }, requestOptions); - }; -}; - -const updateApiKey = (base) => { - return (apiKey, requestOptions) => { - const updatedFields = Object.assign({}, requestOptions); - const { queryParameters, ...options } = requestOptions || {}; - const data = queryParameters ? { queryParameters } : {}; - const apiKeyFields = [ - 'acl', - 'indexes', - 'referers', - 'restrictSources', - 'queryParameters', - 'description', - 'maxQueriesPerIPPerHour', - 'maxHitsPerQuery', - ]; - const hasChanged = (getApiKeyResponse) => { - return Object.keys(updatedFields) - .filter((updatedField) => apiKeyFields.indexOf(updatedField) !== -1) - .every(updatedField => { - return getApiKeyResponse[updatedField] === updatedFields[updatedField]; - }); - }; - const wait = (_, waitRequestOptions) => clientCommon.createRetryablePromise(retry => { - return getApiKey(base)(apiKey, waitRequestOptions).then(getApiKeyResponse => { - return hasChanged(getApiKeyResponse) ? Promise.resolve() : retry(); - }); - }); - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Put, - path: clientCommon.encode('1/keys/%s', apiKey), - data, - }, options), wait); - }; -}; - -const batch = (base) => { - return (requests, requestOptions) => { - const wait = (response, waitRequestOptions) => { - return waitTask(base)(response.taskID, waitRequestOptions); - }; - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/batch', base.indexName), - data: { - requests, - }, - }, requestOptions), wait); - }; -}; - -const browseObjects = (base) => { - return (requestOptions) => { - return createBrowsablePromise({ - shouldStop: response => response.cursor === undefined, - ...requestOptions, - request: (data) => base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/browse', base.indexName), - data, - }, requestOptions), - }); - }; -}; - -const browseRules = (base) => { - return (requestOptions) => { - const options = { - hitsPerPage: 1000, - ...requestOptions, - }; - return createBrowsablePromise({ - shouldStop: response => response.hits.length < options.hitsPerPage, - ...options, - request(data) { - return searchRules(base)('', { ...options, ...data }).then((response) => { - return { - ...response, - hits: response.hits.map(rule => { - // eslint-disable-next-line functional/immutable-data,no-param-reassign - delete rule._highlightResult; - return rule; - }), - }; - }); - }, - }); - }; -}; - -const browseSynonyms = (base) => { - return (requestOptions) => { - const options = { - hitsPerPage: 1000, - ...requestOptions, - }; - return createBrowsablePromise({ - shouldStop: response => response.hits.length < options.hitsPerPage, - ...options, - request(data) { - return searchSynonyms(base)('', { ...options, ...data }).then((response) => { - return { - ...response, - hits: response.hits.map(synonym => { - // eslint-disable-next-line functional/immutable-data,no-param-reassign - delete synonym._highlightResult; - return synonym; - }), - }; - }); - }, - }); - }; -}; - -const chunkedBatch = (base) => { - return (bodies, action, requestOptions) => { - const { batchSize, ...options } = requestOptions || {}; - const response = { - taskIDs: [], - objectIDs: [], - }; - const forEachBatch = (lastIndex = 0) => { - // eslint-disable-next-line functional/prefer-readonly-type - const bodiesChunk = []; - // eslint-disable-next-line functional/no-let - let index; - /* eslint-disable-next-line functional/no-loop-statement */ - for (index = lastIndex; index < bodies.length; index++) { - // eslint-disable-next-line functional/immutable-data - bodiesChunk.push(bodies[index]); - if (bodiesChunk.length === (batchSize || 1000)) { - break; - } - } - if (bodiesChunk.length === 0) { - return Promise.resolve(response); - } - return batch(base)(bodiesChunk.map(body => { - return { - action, - body, - }; - }), options).then(res => { - response.objectIDs = response.objectIDs.concat(res.objectIDs); // eslint-disable-line functional/immutable-data - response.taskIDs.push(res.taskID); // eslint-disable-line functional/immutable-data - index++; - return forEachBatch(index); - }); - }; - return clientCommon.createWaitablePromise(forEachBatch(), (chunkedBatchResponse, waitRequestOptions) => { - return Promise.all(chunkedBatchResponse.taskIDs.map(taskID => { - return waitTask(base)(taskID, waitRequestOptions); - })); - }); - }; -}; - -const clearObjects = (base) => { - return (requestOptions) => { - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/clear', base.indexName), - }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const clearRules = (base) => { - return (requestOptions) => { - const { forwardToReplicas, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/rules/clear', base.indexName), - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const clearSynonyms = (base) => { - return (requestOptions) => { - const { forwardToReplicas, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/synonyms/clear', base.indexName), - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const deleteBy = (base) => { - return (filters, requestOptions) => { - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/deleteByQuery', base.indexName), - data: filters, - }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const deleteIndex = (base) => { - return (requestOptions) => { - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Delete, - path: clientCommon.encode('1/indexes/%s', base.indexName), - }, requestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const deleteObject = (base) => { - return (objectID, requestOptions) => { - return clientCommon.createWaitablePromise(deleteObjects(base)([objectID], requestOptions).then(response => { - return { taskID: response.taskIDs[0] }; - }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const deleteObjects = (base) => { - return (objectIDs, requestOptions) => { - const objects = objectIDs.map(objectID => { - return { objectID }; - }); - return chunkedBatch(base)(objects, BatchActionEnum.DeleteObject, requestOptions); - }; -}; - -const deleteRule = (base) => { - return (objectID, requestOptions) => { - const { forwardToReplicas, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Delete, - path: clientCommon.encode('1/indexes/%s/rules/%s', base.indexName, objectID), - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const deleteSynonym = (base) => { - return (objectID, requestOptions) => { - const { forwardToReplicas, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Delete, - path: clientCommon.encode('1/indexes/%s/synonyms/%s', base.indexName, objectID), - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const exists = (base) => { - return (requestOptions) => { - return getSettings(base)(requestOptions) - .then(() => true) - .catch(error => { - if (error.status !== 404) { - throw error; - } - return false; - }); - }; -}; - -const findAnswers = (base) => { - return (query, queryLanguages, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/answers/%s/prediction', base.indexName), - data: { - query, - queryLanguages, - }, - cacheable: true, - }, requestOptions); - }; -}; - -const findObject = (base) => { - return (callback, requestOptions) => { - const { query, paginate, ...options } = requestOptions || {}; - // eslint-disable-next-line functional/no-let - let page = 0; - const forEachPage = () => { - return search(base)(query || '', { ...options, page }).then(result => { - // eslint-disable-next-line functional/no-loop-statement - for (const [position, hit] of Object.entries(result.hits)) { - // eslint-disable-next-line promise/no-callback-in-promise - if (callback(hit)) { - return { - object: hit, - position: parseInt(position, 10), - page, - }; - } - } - page++; - // paginate if option was set and has next page - if (paginate === false || page >= result.nbPages) { - throw createObjectNotFoundError(); - } - return forEachPage(); - }); - }; - return forEachPage(); - }; -}; - -const getObject = (base) => { - return (objectID, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('1/indexes/%s/%s', base.indexName, objectID), - }, requestOptions); - }; -}; - -const getObjectPosition = () => { - return (searchResponse, objectID) => { - // eslint-disable-next-line functional/no-loop-statement - for (const [position, hit] of Object.entries(searchResponse.hits)) { - if (hit.objectID === objectID) { - return parseInt(position, 10); - } - } - return -1; - }; -}; - -const getObjects = (base) => { - return (objectIDs, requestOptions) => { - const { attributesToRetrieve, ...options } = requestOptions || {}; - const requests = objectIDs.map(objectID => { - return { - indexName: base.indexName, - objectID, - ...(attributesToRetrieve ? { attributesToRetrieve } : {}), - }; - }); - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: '1/indexes/*/objects', - data: { - requests, - }, - }, options); - }; -}; - -const getRule = (base) => { - return (objectID, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('1/indexes/%s/rules/%s', base.indexName, objectID), - }, requestOptions); - }; -}; - -const getSettings = (base) => { - return (requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('1/indexes/%s/settings', base.indexName), - data: { - getVersion: 2, - }, - }, requestOptions); - }; -}; - -const getSynonym = (base) => { - return (objectID, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode(`1/indexes/%s/synonyms/%s`, base.indexName, objectID), - }, requestOptions); - }; -}; - -const getTask = (base) => { - return (taskID, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Get, - path: clientCommon.encode('1/indexes/%s/task/%s', base.indexName, taskID.toString()), - }, requestOptions); - }; -}; - -const partialUpdateObject = (base) => { - return (object, requestOptions) => { - return clientCommon.createWaitablePromise(partialUpdateObjects(base)([object], requestOptions).then(response => { - return { - objectID: response.objectIDs[0], - taskID: response.taskIDs[0], - }; - }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const partialUpdateObjects = (base) => { - return (objects, requestOptions) => { - const { createIfNotExists, ...options } = requestOptions || {}; - const action = createIfNotExists - ? BatchActionEnum.PartialUpdateObject - : BatchActionEnum.PartialUpdateObjectNoCreate; - return chunkedBatch(base)(objects, action, options); - }; -}; - -const replaceAllObjects = (base) => { - return (objects, requestOptions) => { - const { safe, autoGenerateObjectIDIfNotExist, batchSize, ...options } = requestOptions || {}; - const operation = (from, to, type, operationRequestOptions) => { - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/operation', from), - data: { - operation: type, - destination: to, - }, - }, operationRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; - const randomSuffix = Math.random() - .toString(36) - .substring(7); - const temporaryIndexName = `${base.indexName}_tmp_${randomSuffix}`; - const saveObjectsInTemporary = saveObjects({ - appId: base.appId, - transporter: base.transporter, - indexName: temporaryIndexName, - }); - // @ts-ignore - // eslint-disable-next-line prefer-const, functional/no-let, functional/prefer-readonly-type - let responses = []; - const copyWaitablePromise = operation(base.indexName, temporaryIndexName, 'copy', { - ...options, - scope: ['settings', 'synonyms', 'rules'], - }); - // eslint-disable-next-line functional/immutable-data - responses.push(copyWaitablePromise); - const result = (safe - ? copyWaitablePromise.wait(options) - : copyWaitablePromise) - .then(() => { - const saveObjectsWaitablePromise = saveObjectsInTemporary(objects, { - ...options, - autoGenerateObjectIDIfNotExist, - batchSize, - }); - // eslint-disable-next-line functional/immutable-data - responses.push(saveObjectsWaitablePromise); - return safe ? saveObjectsWaitablePromise.wait(options) : saveObjectsWaitablePromise; - }) - .then(() => { - const moveWaitablePromise = operation(temporaryIndexName, base.indexName, 'move', options); - // eslint-disable-next-line functional/immutable-data - responses.push(moveWaitablePromise); - return safe ? moveWaitablePromise.wait(options) : moveWaitablePromise; - }) - .then(() => Promise.all(responses)) - .then(([copyResponse, saveObjectsResponse, moveResponse]) => { - return { - objectIDs: saveObjectsResponse.objectIDs, - taskIDs: [copyResponse.taskID, ...saveObjectsResponse.taskIDs, moveResponse.taskID], - }; - }); - return clientCommon.createWaitablePromise(result, (_, waitRequestOptions) => { - return Promise.all(responses.map(response => response.wait(waitRequestOptions))); - }); - }; -}; - -const replaceAllRules = (base) => { - return (rules, requestOptions) => { - return saveRules(base)(rules, { - ...requestOptions, - clearExistingRules: true, - }); - }; -}; - -const replaceAllSynonyms = (base) => { - return (synonyms, requestOptions) => { - return saveSynonyms(base)(synonyms, { - ...requestOptions, - clearExistingSynonyms: true, - }); - }; -}; - -const saveObject = (base) => { - return (object, requestOptions) => { - return clientCommon.createWaitablePromise(saveObjects(base)([object], requestOptions).then(response => { - return { - objectID: response.objectIDs[0], - taskID: response.taskIDs[0], - }; - }), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const saveObjects = (base) => { - return (objects, requestOptions) => { - const { autoGenerateObjectIDIfNotExist, ...options } = requestOptions || {}; - const action = autoGenerateObjectIDIfNotExist - ? BatchActionEnum.AddObject - : BatchActionEnum.UpdateObject; - if (action === BatchActionEnum.UpdateObject) { - // eslint-disable-next-line functional/no-loop-statement - for (const object of objects) { - if (object.objectID === undefined) { - return clientCommon.createWaitablePromise(Promise.reject(createMissingObjectIDError())); - } - } - } - return chunkedBatch(base)(objects, action, options); - }; -}; - -const saveRule = (base) => { - return (rule, requestOptions) => { - return saveRules(base)([rule], requestOptions); - }; -}; - -const saveRules = (base) => { - return (rules, requestOptions) => { - const { forwardToReplicas, clearExistingRules, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - if (clearExistingRules) { - mappedRequestOptions.queryParameters.clearExistingRules = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/rules/batch', base.indexName), - data: rules, - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const saveSynonym = (base) => { - return (synonym, requestOptions) => { - return saveSynonyms(base)([synonym], requestOptions); - }; -}; - -const saveSynonyms = (base) => { - return (synonyms, requestOptions) => { - const { forwardToReplicas, clearExistingSynonyms, replaceExistingSynonyms, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - if (replaceExistingSynonyms || clearExistingSynonyms) { - mappedRequestOptions.queryParameters.replaceExistingSynonyms = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/synonyms/batch', base.indexName), - data: synonyms, - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const search = (base) => { - return (query, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/query', base.indexName), - data: { - query, - }, - cacheable: true, - }, requestOptions); - }; -}; - -const searchForFacetValues = (base) => { - return (facetName, facetQuery, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/facets/%s/query', base.indexName, facetName), - data: { - facetQuery, - }, - cacheable: true, - }, requestOptions); - }; -}; - -const searchRules = (base) => { - return (query, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/rules/search', base.indexName), - data: { - query, - }, - }, requestOptions); - }; -}; - -const searchSynonyms = (base) => { - return (query, requestOptions) => { - return base.transporter.read({ - method: requesterCommon.MethodEnum.Post, - path: clientCommon.encode('1/indexes/%s/synonyms/search', base.indexName), - data: { - query, - }, - }, requestOptions); - }; -}; - -const setSettings = (base) => { - return (settings, requestOptions) => { - const { forwardToReplicas, ...options } = requestOptions || {}; - const mappedRequestOptions = transporter.createMappedRequestOptions(options); - if (forwardToReplicas) { - mappedRequestOptions.queryParameters.forwardToReplicas = 1; // eslint-disable-line functional/immutable-data - } - return clientCommon.createWaitablePromise(base.transporter.write({ - method: requesterCommon.MethodEnum.Put, - path: clientCommon.encode('1/indexes/%s/settings', base.indexName), - data: settings, - }, mappedRequestOptions), (response, waitRequestOptions) => waitTask(base)(response.taskID, waitRequestOptions)); - }; -}; - -const waitTask = (base) => { - return (taskID, requestOptions) => { - return clientCommon.createRetryablePromise(retry => { - return getTask(base)(taskID, requestOptions).then(response => { - return response.status !== 'published' ? retry() : undefined; - }); - }); - }; -}; - -const ApiKeyACLEnum = { - AddObject: 'addObject', - Analytics: 'analytics', - Browser: 'browse', - DeleteIndex: 'deleteIndex', - DeleteObject: 'deleteObject', - EditSettings: 'editSettings', - ListIndexes: 'listIndexes', - Logs: 'logs', - Recommendation: 'recommendation', - Search: 'search', - SeeUnretrievableAttributes: 'seeUnretrievableAttributes', - Settings: 'settings', - Usage: 'usage', -}; - -const BatchActionEnum = { - AddObject: 'addObject', - UpdateObject: 'updateObject', - PartialUpdateObject: 'partialUpdateObject', - PartialUpdateObjectNoCreate: 'partialUpdateObjectNoCreate', - DeleteObject: 'deleteObject', - DeleteIndex: 'delete', - ClearIndex: 'clear', -}; - -const ScopeEnum = { - Settings: 'settings', - Synonyms: 'synonyms', - Rules: 'rules', -}; - -const StrategyEnum = { - None: 'none', - StopIfEnoughMatches: 'stopIfEnoughMatches', -}; - -const SynonymEnum = { - Synonym: 'synonym', - OneWaySynonym: 'oneWaySynonym', - AltCorrection1: 'altCorrection1', - AltCorrection2: 'altCorrection2', - Placeholder: 'placeholder', -}; - -exports.ApiKeyACLEnum = ApiKeyACLEnum; -exports.BatchActionEnum = BatchActionEnum; -exports.ScopeEnum = ScopeEnum; -exports.StrategyEnum = StrategyEnum; -exports.SynonymEnum = SynonymEnum; -exports.addApiKey = addApiKey; -exports.assignUserID = assignUserID; -exports.assignUserIDs = assignUserIDs; -exports.batch = batch; -exports.browseObjects = browseObjects; -exports.browseRules = browseRules; -exports.browseSynonyms = browseSynonyms; -exports.chunkedBatch = chunkedBatch; -exports.clearObjects = clearObjects; -exports.clearRules = clearRules; -exports.clearSynonyms = clearSynonyms; -exports.copyIndex = copyIndex; -exports.copyRules = copyRules; -exports.copySettings = copySettings; -exports.copySynonyms = copySynonyms; -exports.createBrowsablePromise = createBrowsablePromise; -exports.createMissingObjectIDError = createMissingObjectIDError; -exports.createObjectNotFoundError = createObjectNotFoundError; -exports.createSearchClient = createSearchClient; -exports.createValidUntilNotFoundError = createValidUntilNotFoundError; -exports.deleteApiKey = deleteApiKey; -exports.deleteBy = deleteBy; -exports.deleteIndex = deleteIndex; -exports.deleteObject = deleteObject; -exports.deleteObjects = deleteObjects; -exports.deleteRule = deleteRule; -exports.deleteSynonym = deleteSynonym; -exports.exists = exists; -exports.findAnswers = findAnswers; -exports.findObject = findObject; -exports.generateSecuredApiKey = generateSecuredApiKey; -exports.getApiKey = getApiKey; -exports.getLogs = getLogs; -exports.getObject = getObject; -exports.getObjectPosition = getObjectPosition; -exports.getObjects = getObjects; -exports.getRule = getRule; -exports.getSecuredApiKeyRemainingValidity = getSecuredApiKeyRemainingValidity; -exports.getSettings = getSettings; -exports.getSynonym = getSynonym; -exports.getTask = getTask; -exports.getTopUserIDs = getTopUserIDs; -exports.getUserID = getUserID; -exports.hasPendingMappings = hasPendingMappings; -exports.initIndex = initIndex; -exports.listApiKeys = listApiKeys; -exports.listClusters = listClusters; -exports.listIndices = listIndices; -exports.listUserIDs = listUserIDs; -exports.moveIndex = moveIndex; -exports.multipleBatch = multipleBatch; -exports.multipleGetObjects = multipleGetObjects; -exports.multipleQueries = multipleQueries; -exports.multipleSearchForFacetValues = multipleSearchForFacetValues; -exports.partialUpdateObject = partialUpdateObject; -exports.partialUpdateObjects = partialUpdateObjects; -exports.removeUserID = removeUserID; -exports.replaceAllObjects = replaceAllObjects; -exports.replaceAllRules = replaceAllRules; -exports.replaceAllSynonyms = replaceAllSynonyms; -exports.restoreApiKey = restoreApiKey; -exports.saveObject = saveObject; -exports.saveObjects = saveObjects; -exports.saveRule = saveRule; -exports.saveRules = saveRules; -exports.saveSynonym = saveSynonym; -exports.saveSynonyms = saveSynonyms; -exports.search = search; -exports.searchForFacetValues = searchForFacetValues; -exports.searchRules = searchRules; -exports.searchSynonyms = searchSynonyms; -exports.searchUserIDs = searchUserIDs; -exports.setSettings = setSettings; -exports.updateApiKey = updateApiKey; -exports.waitTask = waitTask; - - -/***/ }), - -/***/ 2425: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(102); - - -/***/ }), - -/***/ 242: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function createNullLogger() { - return { - debug(_message, _args) { - return Promise.resolve(); - }, - info(_message, _args) { - return Promise.resolve(); - }, - error(_message, _args) { - return Promise.resolve(); - }, - }; -} - -const LogLevelEnum = { - Debug: 1, - Info: 2, - Error: 3, -}; - -exports.LogLevelEnum = LogLevelEnum; -exports.createNullLogger = createNullLogger; - - -/***/ }), - -/***/ 3564: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(242); - - -/***/ }), - -/***/ 6721: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -const MethodEnum = { - Delete: 'DELETE', - Get: 'GET', - Post: 'POST', - Put: 'PUT', -}; - -exports.MethodEnum = MethodEnum; - - -/***/ }), - -/***/ 6373: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(6721); - - -/***/ }), - -/***/ 9437: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var http = __webpack_require__(8605); -var https = __webpack_require__(7211); -var URL = __webpack_require__(8835); - -/* eslint functional/prefer-readonly-type: 0 */ -const agentOptions = { keepAlive: true }; -const defaultHttpAgent = new http.Agent(agentOptions); -const defaultHttpsAgent = new https.Agent(agentOptions); -function createNodeHttpRequester({ agent: userGlobalAgent, httpAgent: userHttpAgent, httpsAgent: userHttpsAgent, requesterOptions = {}, } = {}) { - const httpAgent = userHttpAgent || userGlobalAgent || defaultHttpAgent; - const httpsAgent = userHttpsAgent || userGlobalAgent || defaultHttpsAgent; - return { - send(request) { - return new Promise(resolve => { - const url = URL.parse(request.url); - const path = url.query === null ? url.pathname : `${url.pathname}?${url.query}`; - const options = { - ...requesterOptions, - agent: url.protocol === 'https:' ? httpsAgent : httpAgent, - hostname: url.hostname, - path, - method: request.method, - headers: { - ...(requesterOptions && requesterOptions.headers ? requesterOptions.headers : {}), - ...request.headers, - }, - ...(url.port !== undefined ? { port: url.port || '' } : {}), - }; - const req = (url.protocol === 'https:' ? https : http).request(options, response => { - // eslint-disable-next-line functional/no-let - let contentBuffers = []; - response.on('data', chunk => { - contentBuffers = contentBuffers.concat(chunk); - }); - response.on('end', () => { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(connectTimeout); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(responseTimeout); - resolve({ - status: response.statusCode || 0, - content: Buffer.concat(contentBuffers).toString(), - isTimedOut: false, - }); - }); - }); - const createTimeout = (timeout, content) => { - return setTimeout(() => { - req.abort(); - resolve({ - status: 0, - content, - isTimedOut: true, - }); - }, timeout * 1000); - }; - const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); - // eslint-disable-next-line functional/no-let - let responseTimeout; - req.on('error', error => { - clearTimeout(connectTimeout); - clearTimeout(responseTimeout); - resolve({ status: 0, content: error.message, isTimedOut: false }); - }); - req.once('response', () => { - clearTimeout(connectTimeout); - responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); - }); - if (request.data !== undefined) { - req.write(request.data); - } - req.end(); - }); - }, - destroy() { - httpAgent.destroy(); - httpsAgent.destroy(); - return Promise.resolve(); - }, - }; -} - -exports.createNodeHttpRequester = createNodeHttpRequester; - - -/***/ }), - -/***/ 2724: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(9437); - - -/***/ }), - -/***/ 3056: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var requesterCommon = __webpack_require__(6373); - -function createMappedRequestOptions(requestOptions, timeout) { - const options = requestOptions || {}; - const data = options.data || {}; - Object.keys(options).forEach(key => { - if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { - data[key] = options[key]; // eslint-disable-line functional/immutable-data - } - }); - return { - data: Object.entries(data).length > 0 ? data : undefined, - timeout: options.timeout || timeout, - headers: options.headers || {}, - queryParameters: options.queryParameters || {}, - cacheable: options.cacheable, - }; -} - -const CallEnum = { - /** - * If the host is read only. - */ - Read: 1, - /** - * If the host is write only. - */ - Write: 2, - /** - * If the host is both read and write. - */ - Any: 3, -}; - -const HostStatusEnum = { - Up: 1, - Down: 2, - Timeouted: 3, -}; - -// By default, API Clients at Algolia have expiration delay -// of 5 mins. In the JavaScript client, we have 2 mins. -const EXPIRATION_DELAY = 2 * 60 * 1000; -function createStatefulHost(host, status = HostStatusEnum.Up) { - return { - ...host, - status, - lastUpdate: Date.now(), - }; -} -function isStatefulHostUp(host) { - return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; -} -function isStatefulHostTimeouted(host) { - return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); -} - -function createStatelessHost(options) { - if (typeof options === 'string') { - return { - protocol: 'https', - url: options, - accept: CallEnum.Any, - }; - } - return { - protocol: options.protocol || 'https', - url: options.url, - accept: options.accept || CallEnum.Any, - }; -} - -function createRetryableOptions(hostsCache, statelessHosts) { - return Promise.all(statelessHosts.map(statelessHost => { - return hostsCache.get(statelessHost, () => { - return Promise.resolve(createStatefulHost(statelessHost)); - }); - })).then(statefulHosts => { - const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); - const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); - /** - * Note, we put the hosts that previously timeouted on the end of the list. - */ - const hostsAvailable = [...hostsUp, ...hostsTimeouted]; - const statelessHostsAvailable = hostsAvailable.length > 0 - ? hostsAvailable.map(host => createStatelessHost(host)) - : statelessHosts; - return { - getTimeout(timeoutsCount, baseTimeout) { - /** - * Imagine that you have 4 hosts, if timeouts will increase - * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) - * - * Note that, the very next request, we start from the previous timeout - * - * 5 (timeouted) > 6 (timeouted) > 7 ... - * - * This strategy may need to be reviewed, but is the strategy on the our - * current v3 version. - */ - const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 - ? 1 - : hostsTimeouted.length + 3 + timeoutsCount; - return timeoutMultiplier * baseTimeout; - }, - statelessHosts: statelessHostsAvailable, - }; - }); -} - -const isNetworkError = ({ isTimedOut, status }) => { - return !isTimedOut && ~~status === 0; -}; -const isRetryable = (response) => { - const status = response.status; - const isTimedOut = response.isTimedOut; - return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); -}; -const isSuccess = ({ status }) => { - return ~~(status / 100) === 2; -}; -const retryDecision = (response, outcomes) => { - if (isRetryable(response)) { - return outcomes.onRetry(response); - } - if (isSuccess(response)) { - return outcomes.onSucess(response); - } - return outcomes.onFail(response); -}; - -function retryableRequest(transporter, statelessHosts, request, requestOptions) { - const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type - /** - * First we prepare the payload that do not depend from hosts. - */ - const data = serializeData(request, requestOptions); - const headers = serializeHeaders(transporter, requestOptions); - const method = request.method; - // On `GET`, the data is proxied to query parameters. - const dataQueryParameters = request.method !== requesterCommon.MethodEnum.Get - ? {} - : { - ...request.data, - ...requestOptions.data, - }; - const queryParameters = { - 'x-algolia-agent': transporter.userAgent.value, - ...transporter.queryParameters, - ...dataQueryParameters, - ...requestOptions.queryParameters, - }; - let timeoutsCount = 0; // eslint-disable-line functional/no-let - const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type - getTimeout) => { - /** - * We iterate on each host, until there is no host left. - */ - const host = hosts.pop(); // eslint-disable-line functional/immutable-data - if (host === undefined) { - throw createRetryError(stackTraceWithoutCredentials(stackTrace)); - } - const payload = { - data, - headers, - method, - url: serializeUrl(host, request.path, queryParameters), - connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), - responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), - }; - /** - * The stackFrame is pushed to the stackTrace so we - * can have information about onRetry and onFailure - * decisions. - */ - const pushToStackTrace = (response) => { - const stackFrame = { - request: payload, - response, - host, - triesLeft: hosts.length, - }; - // eslint-disable-next-line functional/immutable-data - stackTrace.push(stackFrame); - return stackFrame; - }; - const decisions = { - onSucess: response => deserializeSuccess(response), - onRetry(response) { - const stackFrame = pushToStackTrace(response); - /** - * If response is a timeout, we increaset the number of - * timeouts so we can increase the timeout later. - */ - if (response.isTimedOut) { - timeoutsCount++; - } - return Promise.all([ - /** - * Failures are individually send the logger, allowing - * the end user to debug / store stack frames even - * when a retry error does not happen. - */ - transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), - /** - * We also store the state of the host in failure cases. If the host, is - * down it will remain down for the next 2 minutes. In a timeout situation, - * this host will be added end of the list of hosts on the next request. - */ - transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), - ]).then(() => retry(hosts, getTimeout)); - }, - onFail(response) { - pushToStackTrace(response); - throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); - }, - }; - return transporter.requester.send(payload).then(response => { - return retryDecision(response, decisions); - }); - }; - /** - * Finally, for each retryable host perform request until we got a non - * retryable response. Some notes here: - * - * 1. The reverse here is applied so we can apply a `pop` later on => more performant. - * 2. We also get from the retryable options a timeout multiplier that is tailored - * for the current context. - */ - return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { - return retry([...options.statelessHosts].reverse(), options.getTimeout); - }); -} - -function createTransporter(options) { - const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; - const transporter = { - hostsCache, - logger, - requester, - requestsCache, - responsesCache, - timeouts, - userAgent, - headers, - queryParameters, - hosts: hosts.map(host => createStatelessHost(host)), - read(request, requestOptions) { - /** - * First, we compute the user request options. Now, keep in mind, - * that using request options the user is able to modified the intire - * payload of the request. Such as headers, query parameters, and others. - */ - const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); - const createRetryableRequest = () => { - /** - * Then, we prepare a function factory that contains the construction of - * the retryable request. At this point, we may *not* perform the actual - * request. But we want to have the function factory ready. - */ - return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); - }; - /** - * Once we have the function factory ready, we need to determine of the - * request is "cacheable" - should be cached. Note that, once again, - * the user can force this option. - */ - const cacheable = mappedRequestOptions.cacheable !== undefined - ? mappedRequestOptions.cacheable - : request.cacheable; - /** - * If is not "cacheable", we immediatly trigger the retryable request, no - * need to check cache implementations. - */ - if (cacheable !== true) { - return createRetryableRequest(); - } - /** - * If the request is "cacheable", we need to first compute the key to ask - * the cache implementations if this request is on progress or if the - * response already exists on the cache. - */ - const key = { - request, - mappedRequestOptions, - transporter: { - queryParameters: transporter.queryParameters, - headers: transporter.headers, - }, - }; - /** - * With the computed key, we first ask the responses cache - * implemention if this request was been resolved before. - */ - return transporter.responsesCache.get(key, () => { - /** - * If the request has never resolved before, we actually ask if there - * is a current request with the same key on progress. - */ - return transporter.requestsCache.get(key, () => { - return (transporter.requestsCache - /** - * Finally, if there is no request in progress with the same key, - * this `createRetryableRequest()` will actually trigger the - * retryable request. - */ - .set(key, createRetryableRequest()) - .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) - .then(([_, response]) => response)); - }); - }, { - /** - * Of course, once we get this response back from the server, we - * tell response cache to actually store the received response - * to be used later. - */ - miss: response => transporter.responsesCache.set(key, response), - }); - }, - write(request, requestOptions) { - /** - * On write requests, no cache mechanisms are applied, and we - * proxy the request immediately to the requester. - */ - return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); - }, - }; - return transporter; -} - -function createUserAgent(version) { - const userAgent = { - value: `Algolia for JavaScript (${version})`, - add(options) { - const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; - if (userAgent.value.indexOf(addedUserAgent) === -1) { - // eslint-disable-next-line functional/immutable-data - userAgent.value = `${userAgent.value}${addedUserAgent}`; - } - return userAgent; - }, - }; - return userAgent; -} - -function deserializeSuccess(response) { - // eslint-disable-next-line functional/no-try-statement - try { - return JSON.parse(response.content); - } - catch (e) { - throw createDeserializationError(e.message, response); - } -} -function deserializeFailure({ content, status }, stackFrame) { - // eslint-disable-next-line functional/no-let - let message = content; - // eslint-disable-next-line functional/no-try-statement - try { - message = JSON.parse(content).message; - } - catch (e) { - // .. - } - return createApiError(message, status, stackFrame); -} - -// eslint-disable-next-line functional/prefer-readonly-type -function encode(format, ...args) { - // eslint-disable-next-line functional/no-let - let i = 0; - return format.replace(/%s/g, () => encodeURIComponent(args[i++])); -} - -function serializeUrl(host, path, queryParameters) { - const queryParametersAsString = serializeQueryParameters(queryParameters); - // eslint-disable-next-line functional/no-let - let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; - if (queryParametersAsString.length) { - url += `?${queryParametersAsString}`; - } - return url; -} -function serializeQueryParameters(parameters) { - const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || - Object.prototype.toString.call(value) === '[object Array]'; - return Object.keys(parameters) - .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) - .join('&'); -} -function serializeData(request, requestOptions) { - if (request.method === requesterCommon.MethodEnum.Get || - (request.data === undefined && requestOptions.data === undefined)) { - return undefined; - } - const data = Array.isArray(request.data) - ? request.data - : { ...request.data, ...requestOptions.data }; - return JSON.stringify(data); -} -function serializeHeaders(transporter, requestOptions) { - const headers = { - ...transporter.headers, - ...requestOptions.headers, - }; - const serializedHeaders = {}; - Object.keys(headers).forEach(header => { - const value = headers[header]; - // @ts-ignore - // eslint-disable-next-line functional/immutable-data - serializedHeaders[header.toLowerCase()] = value; - }); - return serializedHeaders; -} - -function stackTraceWithoutCredentials(stackTrace) { - return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); -} -function stackFrameWithoutCredentials(stackFrame) { - const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] - ? { 'x-algolia-api-key': '*****' } - : {}; - return { - ...stackFrame, - request: { - ...stackFrame.request, - headers: { - ...stackFrame.request.headers, - ...modifiedHeaders, - }, - }, - }; -} - -function createApiError(message, status, transporterStackTrace) { - return { - name: 'ApiError', - message, - status, - transporterStackTrace, - }; -} - -function createDeserializationError(message, response) { - return { - name: 'DeserializationError', - message, - response, - }; -} - -function createRetryError(transporterStackTrace) { - return { - name: 'RetryError', - message: 'Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.', - transporterStackTrace, - }; -} - -exports.CallEnum = CallEnum; -exports.HostStatusEnum = HostStatusEnum; -exports.createApiError = createApiError; -exports.createDeserializationError = createDeserializationError; -exports.createMappedRequestOptions = createMappedRequestOptions; -exports.createRetryError = createRetryError; -exports.createStatefulHost = createStatefulHost; -exports.createStatelessHost = createStatelessHost; -exports.createTransporter = createTransporter; -exports.createUserAgent = createUserAgent; -exports.deserializeFailure = deserializeFailure; -exports.deserializeSuccess = deserializeSuccess; -exports.isStatefulHostTimeouted = isStatefulHostTimeouted; -exports.isStatefulHostUp = isStatefulHostUp; -exports.serializeData = serializeData; -exports.serializeHeaders = serializeHeaders; -exports.serializeQueryParameters = serializeQueryParameters; -exports.serializeUrl = serializeUrl; -exports.stackFrameWithoutCredentials = stackFrameWithoutCredentials; -exports.stackTraceWithoutCredentials = stackTraceWithoutCredentials; - - -/***/ }), - -/***/ 2424: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// eslint-disable-next-line functional/immutable-data, import/no-commonjs -module.exports = __webpack_require__(3056); - - -/***/ }), - -/***/ 447: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var cacheCommon = __webpack_require__(8848); -var cacheInMemory = __webpack_require__(8069); -var clientAnalytics = __webpack_require__(7538); -var clientCommon = __webpack_require__(1905); -var clientRecommendation = __webpack_require__(31); -var clientSearch = __webpack_require__(2425); -var loggerCommon = __webpack_require__(3564); -var requesterNodeHttp = __webpack_require__(2724); -var transporter = __webpack_require__(2424); - -function algoliasearch(appId, apiKey, options) { - const commonOptions = { - appId, - apiKey, - timeouts: { - connect: 2, - read: 5, - write: 30, - }, - requester: requesterNodeHttp.createNodeHttpRequester(), - logger: loggerCommon.createNullLogger(), - responsesCache: cacheCommon.createNullCache(), - requestsCache: cacheCommon.createNullCache(), - hostsCache: cacheInMemory.createInMemoryCache(), - userAgent: transporter.createUserAgent(clientCommon.version).add({ - segment: 'Node.js', - version: process.versions.node, - }), - }; - return clientSearch.createSearchClient({ - ...commonOptions, - ...options, - methods: { - search: clientSearch.multipleQueries, - searchForFacetValues: clientSearch.multipleSearchForFacetValues, - multipleBatch: clientSearch.multipleBatch, - multipleGetObjects: clientSearch.multipleGetObjects, - multipleQueries: clientSearch.multipleQueries, - copyIndex: clientSearch.copyIndex, - copySettings: clientSearch.copySettings, - copyRules: clientSearch.copyRules, - copySynonyms: clientSearch.copySynonyms, - moveIndex: clientSearch.moveIndex, - listIndices: clientSearch.listIndices, - getLogs: clientSearch.getLogs, - listClusters: clientSearch.listClusters, - multipleSearchForFacetValues: clientSearch.multipleSearchForFacetValues, - getApiKey: clientSearch.getApiKey, - addApiKey: clientSearch.addApiKey, - listApiKeys: clientSearch.listApiKeys, - updateApiKey: clientSearch.updateApiKey, - deleteApiKey: clientSearch.deleteApiKey, - restoreApiKey: clientSearch.restoreApiKey, - assignUserID: clientSearch.assignUserID, - assignUserIDs: clientSearch.assignUserIDs, - getUserID: clientSearch.getUserID, - searchUserIDs: clientSearch.searchUserIDs, - listUserIDs: clientSearch.listUserIDs, - getTopUserIDs: clientSearch.getTopUserIDs, - removeUserID: clientSearch.removeUserID, - hasPendingMappings: clientSearch.hasPendingMappings, - generateSecuredApiKey: clientSearch.generateSecuredApiKey, - getSecuredApiKeyRemainingValidity: clientSearch.getSecuredApiKeyRemainingValidity, - destroy: clientCommon.destroy, - initIndex: base => (indexName) => { - return clientSearch.initIndex(base)(indexName, { - methods: { - batch: clientSearch.batch, - delete: clientSearch.deleteIndex, - findAnswers: clientSearch.findAnswers, - getObject: clientSearch.getObject, - getObjects: clientSearch.getObjects, - saveObject: clientSearch.saveObject, - saveObjects: clientSearch.saveObjects, - search: clientSearch.search, - searchForFacetValues: clientSearch.searchForFacetValues, - waitTask: clientSearch.waitTask, - setSettings: clientSearch.setSettings, - getSettings: clientSearch.getSettings, - partialUpdateObject: clientSearch.partialUpdateObject, - partialUpdateObjects: clientSearch.partialUpdateObjects, - deleteObject: clientSearch.deleteObject, - deleteObjects: clientSearch.deleteObjects, - deleteBy: clientSearch.deleteBy, - clearObjects: clientSearch.clearObjects, - browseObjects: clientSearch.browseObjects, - getObjectPosition: clientSearch.getObjectPosition, - findObject: clientSearch.findObject, - exists: clientSearch.exists, - saveSynonym: clientSearch.saveSynonym, - saveSynonyms: clientSearch.saveSynonyms, - getSynonym: clientSearch.getSynonym, - searchSynonyms: clientSearch.searchSynonyms, - browseSynonyms: clientSearch.browseSynonyms, - deleteSynonym: clientSearch.deleteSynonym, - clearSynonyms: clientSearch.clearSynonyms, - replaceAllObjects: clientSearch.replaceAllObjects, - replaceAllSynonyms: clientSearch.replaceAllSynonyms, - searchRules: clientSearch.searchRules, - getRule: clientSearch.getRule, - deleteRule: clientSearch.deleteRule, - saveRule: clientSearch.saveRule, - saveRules: clientSearch.saveRules, - replaceAllRules: clientSearch.replaceAllRules, - browseRules: clientSearch.browseRules, - clearRules: clientSearch.clearRules, - }, - }); - }, - initAnalytics: () => (clientOptions) => { - return clientAnalytics.createAnalyticsClient({ - ...commonOptions, - ...clientOptions, - methods: { - addABTest: clientAnalytics.addABTest, - getABTest: clientAnalytics.getABTest, - getABTests: clientAnalytics.getABTests, - stopABTest: clientAnalytics.stopABTest, - deleteABTest: clientAnalytics.deleteABTest, - }, - }); - }, - initRecommendation: () => (clientOptions) => { - return clientRecommendation.createRecommendationClient({ - ...commonOptions, - ...clientOptions, - methods: { - getPersonalizationStrategy: clientRecommendation.getPersonalizationStrategy, - setPersonalizationStrategy: clientRecommendation.setPersonalizationStrategy, - }, - }); - }, - }, - }); -} -// eslint-disable-next-line functional/immutable-data -algoliasearch.version = clientCommon.version; - -module.exports = algoliasearch; - - -/***/ }), - -/***/ 930: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/* eslint-disable functional/immutable-data, import/no-commonjs */ -const algoliasearch = __webpack_require__(447); - -/** - * The Common JS build is the default entry point for the Node environment. Keep in - * in mind, that for the browser environment, we hint the bundler to use the UMD - * build instead as specified on the key `browser` of our `package.json` file. - */ -module.exports = algoliasearch; - -/** - * In addition, we also set explicitly the default export below making - * this Common JS module in compliance with es6 modules specification. - */ -module.exports.default = algoliasearch; - - -/***/ }), - -/***/ 7240: -/***/ ((module) => { - -"use strict"; - - -module.exports = bail - -function bail(err) { - if (err) { - throw err - } -} - - -/***/ }), - -/***/ 421: -/***/ ((module) => { - -var charenc = { - // UTF-8 encoding - utf8: { - // Convert a string to a byte array - stringToBytes: function(str) { - return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); + } + function escapeData(s) { + return utils_1 + .toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + } + function escapeProperty(s) { + return utils_1 + .toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C') + } + //# sourceMappingURL=command.js.map + + /***/ }, - // Convert a byte array to a string - bytesToString: function(bytes) { - return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); - } - }, - - // Binary encoding - bin: { - // Convert a string to a byte array - stringToBytes: function(str) { - for (var bytes = [], i = 0; i < str.length; i++) - bytes.push(str.charCodeAt(i) & 0xFF); - return bytes; + /***/ 2186: /***/ function ( + __unused_webpack_module, + exports, + __webpack_require__ + ) { + 'use strict' + + 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 __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod + var result = {} + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k] + result['default'] = mod + return result + } + Object.defineProperty(exports, '__esModule', { value: true }) + const command_1 = __webpack_require__(7351) + const file_command_1 = __webpack_require__(717) + const utils_1 = __webpack_require__(5278) + const os = __importStar(__webpack_require__(2087)) + const path = __importStar(__webpack_require__(5622)) + /** + * The code to exit an action + */ + var ExitCode + ;(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[(ExitCode['Success'] = 0)] = 'Success' + /** + * A code indicating that the action was a failure + */ + ExitCode[(ExitCode['Failure'] = 1)] = 'Failure' + })((ExitCode = exports.ExitCode || (exports.ExitCode = {}))) + //----------------------------------------------------------------------- + // Variables + //----------------------------------------------------------------------- + /** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val) + process.env[name] = convertedVal + const filePath = process.env['GITHUB_ENV'] || '' + if (filePath) { + const delimiter = '_GitHubActionsFileCommandDelimeter_' + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}` + file_command_1.issueCommand('ENV', commandValue) + } else { + command_1.issueCommand('set-env', { name }, convertedVal) + } + } + exports.exportVariable = exportVariable + /** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ + function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret) + } + exports.setSecret = setSecret + /** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ + function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || '' + if (filePath) { + file_command_1.issueCommand('PATH', inputPath) + } else { + command_1.issueCommand('add-path', {}, inputPath) + } + process.env[ + 'PATH' + ] = `${inputPath}${path.delimiter}${process.env['PATH']}` + } + exports.addPath = addPath + /** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ + function getInput(name, options) { + const val = + process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '' + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`) + } + return val.trim() + } + exports.getInput = getInput + /** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value) + } + exports.setOutput = setOutput + /** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ + function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off') + } + exports.setCommandEcho = setCommandEcho + //----------------------------------------------------------------------- + // Results + //----------------------------------------------------------------------- + /** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ + function setFailed(message) { + process.exitCode = ExitCode.Failure + error(message) + } + exports.setFailed = setFailed + //----------------------------------------------------------------------- + // Logging Commands + //----------------------------------------------------------------------- + /** + * Gets whether Actions Step Debug is on or not + */ + function isDebug() { + return process.env['RUNNER_DEBUG'] === '1' + } + exports.isDebug = isDebug + /** + * Writes debug message to user log + * @param message debug message + */ + function debug(message) { + command_1.issueCommand('debug', {}, message) + } + exports.debug = debug + /** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ + function error(message) { + command_1.issue( + 'error', + message instanceof Error ? message.toString() : message + ) + } + exports.error = error + /** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ + function warning(message) { + command_1.issue( + 'warning', + message instanceof Error ? message.toString() : message + ) + } + exports.warning = warning + /** + * Writes info to log with console.log. + * @param message info message + */ + function info(message) { + process.stdout.write(message + os.EOL) + } + exports.info = info + /** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ + function startGroup(name) { + command_1.issue('group', name) + } + exports.startGroup = startGroup + /** + * End an output group. + */ + function endGroup() { + command_1.issue('endgroup') + } + exports.endGroup = endGroup + /** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ + function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name) + let result + try { + result = yield fn() + } finally { + endGroup() + } + return result + }) + } + exports.group = group + //----------------------------------------------------------------------- + // Wrapper action state + //----------------------------------------------------------------------- + /** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value) + } + exports.saveState = saveState + /** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ + function getState(name) { + return process.env[`STATE_${name}`] || '' + } + exports.getState = getState + //# sourceMappingURL=core.js.map + + /***/ }, - // Convert a byte array to a string - bytesToString: function(bytes) { - for (var str = [], i = 0; i < bytes.length; i++) - str.push(String.fromCharCode(bytes[i])); - return str.join(''); - } - } -}; + /***/ 717: /***/ function ( + __unused_webpack_module, + exports, + __webpack_require__ + ) { + 'use strict' + + // For internal use, subject to change. + var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod + var result = {} + if (mod != null) + for (var k in mod) + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k] + result['default'] = mod + return result + } + Object.defineProperty(exports, '__esModule', { value: true }) + // We use any as a valid input type + /* eslint-disable @typescript-eslint/no-explicit-any */ + const fs = __importStar(__webpack_require__(5747)) + const os = __importStar(__webpack_require__(2087)) + const utils_1 = __webpack_require__(5278) + function issueCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`] + if (!filePath) { + throw new Error( + `Unable to find environment variable for file command ${command}` + ) + } + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`) + } + fs.appendFileSync( + filePath, + `${utils_1.toCommandValue(message)}${os.EOL}`, + { + encoding: 'utf8' + } + ) + } + exports.issueCommand = issueCommand + //# sourceMappingURL=file-command.js.map -module.exports = charenc; + /***/ + }, + /***/ 5278: /***/ (__unused_webpack_module, exports) => { + 'use strict' + + // We use any as a valid input type + /* eslint-disable @typescript-eslint/no-explicit-any */ + Object.defineProperty(exports, '__esModule', { value: true }) + /** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ + function toCommandValue(input) { + if (input === null || input === undefined) { + return '' + } else if (typeof input === 'string' || input instanceof String) { + return input + } + return JSON.stringify(input) + } + exports.toCommandValue = toCommandValue + //# sourceMappingURL=utils.js.map -/***/ }), + /***/ + }, -/***/ 2194: -/***/ ((__unused_webpack_module, exports) => { + /***/ 3818: /***/ (__unused_webpack_module, exports) => { + 'use strict' -"use strict"; + Object.defineProperty(exports, '__esModule', { value: true }) + // @todo Add logger on options to debug when caches go wrong. + function createFallbackableCache(options) { + const caches = [...options.caches] + const current = caches.shift() // eslint-disable-line functional/immutable-data + if (current === undefined) { + return createNullCache() + } + return { + get( + key, + defaultValue, + events = { + miss: () => Promise.resolve() + } + ) { + return current.get(key, defaultValue, events).catch(() => { + return createFallbackableCache({ caches }).get( + key, + defaultValue, + events + ) + }) + }, + set(key, value) { + return current.set(key, value).catch(() => { + return createFallbackableCache({ caches }).set(key, value) + }) + }, + delete(key) { + return current.delete(key).catch(() => { + return createFallbackableCache({ caches }).delete(key) + }) + }, + clear() { + return current.clear().catch(() => { + return createFallbackableCache({ caches }).clear() + }) + } + } + } -exports.parse = parse -exports.stringify = stringify + function createNullCache() { + return { + get( + _key, + defaultValue, + events = { + miss: () => Promise.resolve() + } + ) { + const value = defaultValue() + return value + .then((result) => Promise.all([result, events.miss(result)])) + .then(([result]) => result) + }, + set(_key, value) { + return Promise.resolve(value) + }, + delete(_key) { + return Promise.resolve() + }, + clear() { + return Promise.resolve() + } + } + } -var comma = ',' -var space = ' ' -var empty = '' + exports.createFallbackableCache = createFallbackableCache + exports.createNullCache = createNullCache -// Parse comma-separated tokens to an array. -function parse(value) { - var values = [] - var input = String(value || empty) - var index = input.indexOf(comma) - var lastIndex = 0 - var end = false - var val + /***/ + }, - while (!end) { - if (index === -1) { - index = input.length - end = true - } + /***/ 8848: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(3818) - val = input.slice(lastIndex, index).trim() + /***/ + }, - if (val || !end) { - values.push(val) - } + /***/ 2703: /***/ (__unused_webpack_module, exports) => { + 'use strict' - lastIndex = index + 1 - index = input.indexOf(comma, lastIndex) - } + Object.defineProperty(exports, '__esModule', { value: true }) - return values -} + function createInMemoryCache(options = { serializable: true }) { + // eslint-disable-next-line functional/no-let + let cache = {} + return { + get( + key, + defaultValue, + events = { + miss: () => Promise.resolve() + } + ) { + const keyAsString = JSON.stringify(key) + if (keyAsString in cache) { + return Promise.resolve( + options.serializable + ? JSON.parse(cache[keyAsString]) + : cache[keyAsString] + ) + } + const promise = defaultValue() + const miss = (events && events.miss) || (() => Promise.resolve()) + return promise.then((value) => miss(value)).then(() => promise) + }, + set(key, value) { + // eslint-disable-next-line functional/immutable-data + cache[JSON.stringify(key)] = options.serializable + ? JSON.stringify(value) + : value + return Promise.resolve(value) + }, + delete(key) { + // eslint-disable-next-line functional/immutable-data + delete cache[JSON.stringify(key)] + return Promise.resolve() + }, + clear() { + cache = {} + return Promise.resolve() + } + } + } -// Compile an array to comma-separated tokens. -// `options.padLeft` (default: `true`) pads a space left of each token, and -// `options.padRight` (default: `false`) pads a space to the right of each token. -function stringify(values, options) { - var settings = options || {} - var left = settings.padLeft === false ? empty : space - var right = settings.padRight ? space : empty + exports.createInMemoryCache = createInMemoryCache - // Ensure the last empty entry is seen. - if (values[values.length - 1] === empty) { - values = values.concat(empty) - } + /***/ + }, - return values.join(right + comma + left).trim() -} + /***/ 8069: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(2703) + /***/ + }, -/***/ }), + /***/ 6675: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + var clientCommon = __webpack_require__(1905) + var transporter = __webpack_require__(2424) + var requesterCommon = __webpack_require__(6373) + + const createAnalyticsClient = (options) => { + const region = options.region || 'us' + const auth = clientCommon.createAuth( + clientCommon.AuthMode.WithinHeaders, + options.appId, + options.apiKey + ) + const transporter$1 = transporter.createTransporter({ + hosts: [{ url: `analytics.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters + } + }) + const appId = options.appId + return clientCommon.addMethods( + { appId, transporter: transporter$1 }, + options.methods + ) + } -/***/ 7935: -/***/ ((module) => { + const addABTest = (base) => { + return (abTest, requestOptions) => { + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: '2/abtests', + data: abTest + }, + requestOptions + ) + } + } -(function() { - var base64map - = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', + const deleteABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('2/abtests/%s', abTestID) + }, + requestOptions + ) + } + } - crypt = { - // Bit-wise rotation left - rotl: function(n, b) { - return (n << b) | (n >>> (32 - b)); - }, + const getABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('2/abtests/%s', abTestID) + }, + requestOptions + ) + } + } - // Bit-wise rotation right - rotr: function(n, b) { - return (n << (32 - b)) | (n >>> b); - }, + const getABTests = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '2/abtests' + }, + requestOptions + ) + } + } - // Swap big-endian to little-endian and vice versa - endian: function(n) { - // If number given, swap endian - if (n.constructor == Number) { - return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; + const stopABTest = (base) => { + return (abTestID, requestOptions) => { + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('2/abtests/%s/stop', abTestID) + }, + requestOptions + ) + } } - // Else, assume array and swap all items - for (var i = 0; i < n.length; i++) - n[i] = crypt.endian(n[i]); - return n; - }, + exports.addABTest = addABTest + exports.createAnalyticsClient = createAnalyticsClient + exports.deleteABTest = deleteABTest + exports.getABTest = getABTest + exports.getABTests = getABTests + exports.stopABTest = stopABTest - // Generate an array of any length of random bytes - randomBytes: function(n) { - for (var bytes = []; n > 0; n--) - bytes.push(Math.floor(Math.random() * 256)); - return bytes; + /***/ }, - // Convert a byte array to big-endian 32-bit words - bytesToWords: function(bytes) { - for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) - words[b >>> 5] |= bytes[i] << (24 - b % 32); - return words; - }, + /***/ 7538: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(6675) - // Convert big-endian 32-bit words to a byte array - wordsToBytes: function(words) { - for (var bytes = [], b = 0; b < words.length * 32; b += 8) - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); - return bytes; + /***/ }, - // Convert a byte array to a hex string - bytesToHex: function(bytes) { - for (var hex = [], i = 0; i < bytes.length; i++) { - hex.push((bytes[i] >>> 4).toString(16)); - hex.push((bytes[i] & 0xF).toString(16)); - } - return hex.join(''); - }, + /***/ 5526: /***/ (__unused_webpack_module, exports) => { + 'use strict' - // Convert a hex string to a byte array - hexToBytes: function(hex) { - for (var bytes = [], c = 0; c < hex.length; c += 2) - bytes.push(parseInt(hex.substr(c, 2), 16)); - return bytes; - }, + Object.defineProperty(exports, '__esModule', { value: true }) - // Convert a byte array to a base-64 string - bytesToBase64: function(bytes) { - for (var base64 = [], i = 0; i < bytes.length; i += 3) { - var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - for (var j = 0; j < 4; j++) - if (i * 8 + j * 6 <= bytes.length * 8) - base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); - else - base64.push('='); - } - return base64.join(''); - }, + function createAuth(authMode, appId, apiKey) { + const credentials = { + 'x-algolia-api-key': apiKey, + 'x-algolia-application-id': appId + } + return { + headers() { + return authMode === AuthMode.WithinHeaders ? credentials : {} + }, + queryParameters() { + return authMode === AuthMode.WithinQueryParameters + ? credentials + : {} + } + } + } - // Convert a base-64 string to a byte array - base64ToBytes: function(base64) { - // Remove non-base-64 characters - base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); + function createRetryablePromise(callback) { + let retriesCount = 0 // eslint-disable-line functional/no-let + const retry = () => { + retriesCount++ + return new Promise((resolve) => { + setTimeout(() => { + resolve(callback(retry)) + }, Math.min(100 * retriesCount, 1000)) + }) + } + return callback(retry) + } - for (var bytes = [], i = 0, imod4 = 0; i < base64.length; - imod4 = ++i % 4) { - if (imod4 == 0) continue; - bytes.push(((base64map.indexOf(base64.charAt(i - 1)) - & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) - | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + function createWaitablePromise( + promise, + wait = (_response, _requestOptions) => { + return Promise.resolve() + } + ) { + // eslint-disable-next-line functional/immutable-data + return Object.assign(promise, { + wait(requestOptions) { + return createWaitablePromise( + promise + .then((response) => + Promise.all([wait(response, requestOptions), response]) + ) + .then((promiseResults) => promiseResults[1]) + ) + } + }) } - return bytes; - } - }; - - module.exports = crypt; -})(); - - -/***/ }), - -/***/ 8171: -/***/ ((module) => { - -"use strict"; - - -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var defineProperty = Object.defineProperty; -var gOPD = Object.getOwnPropertyDescriptor; - -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } - - return toStr.call(arr) === '[object Array]'; -}; - -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } - - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) { /**/ } - - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; - -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target -var setProperty = function setProperty(target, options) { - if (defineProperty && options.name === '__proto__') { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } -}; - -// Return undefined instead of __proto__ if '__proto__' is not an own property -var getProperty = function getProperty(obj, name) { - if (name === '__proto__') { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - // In early versions of node, obj['__proto__'] is buggy when obj has - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. - return gOPD(obj, name).value; - } - } - - return obj[name]; -}; - -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; - - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { - target = {}; - } - - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); - - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); - - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - setProperty(target, { name: name, newValue: copy }); - } - } - } - } - } - - // Return the modified object - return target; -}; - - -/***/ }), - -/***/ 237: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var emoji = __webpack_require__(5464) - -module.exports = BananaSlug - -var own = Object.hasOwnProperty -var whitespace = /\s/g -var specials = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~’]/g - -function BananaSlug () { - var self = this - - if (!(self instanceof BananaSlug)) return new BananaSlug() - - self.reset() -} - -/** - * Generate a unique slug. - * @param {string} value String of text to slugify - * @param {boolean} [false] Keep the current case, otherwise make all lowercase - * @return {string} A unique slug string - */ -BananaSlug.prototype.slug = function (value, maintainCase) { - var self = this - var slug = slugger(value, maintainCase === true) - var originalSlug = slug - - while (own.call(self.occurrences, slug)) { - self.occurrences[originalSlug]++ - slug = originalSlug + '-' + self.occurrences[originalSlug] - } - - self.occurrences[slug] = 0 - - return slug -} - -/** - * Reset - Forget all previous slugs - * @return void - */ -BananaSlug.prototype.reset = function () { - this.occurrences = Object.create(null) -} - -function slugger (string, maintainCase) { - if (typeof string !== 'string') return '' - if (!maintainCase) string = string.toLowerCase() - - return string.trim() - .replace(specials, '') - .replace(emoji(), '') - .replace(whitespace, '-') -} - -BananaSlug.slug = slugger - - -/***/ }), - -/***/ 5464: -/***/ ((module) => { - -module.exports = function() { - return /[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267B\u267F\u2692-\u2694\u2696\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD79\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED0\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3]|\uD83E[\uDD10-\uDD18\uDD80-\uDD84\uDDC0]|\uD83C\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uD83C\uDDFE\uD83C[\uDDEA\uDDF9]|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDFC\uD83C[\uDDEB\uDDF8]|\uD83C\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uD83C\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF8\uDDFE\uDDFF]|\uD83C\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uD83C\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uD83C\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uD83C\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uD83C\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uD83C\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uD83C\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uD83C\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uD83C\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uD83C\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uD83C\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uD83C\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uD83C\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uD83C\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uD83C\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uD83C\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|[#\*0-9]\u20E3/g; -}; - - -/***/ }), - -/***/ 4547: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var html = __webpack_require__(9515) -var svg = __webpack_require__(4589) -var find = __webpack_require__(3657) -var hastToReact = __webpack_require__(3934) -var spaces = __webpack_require__(4158) -var commas = __webpack_require__(2194) -var style = __webpack_require__(6204) -var ns = __webpack_require__(4992) -var convert = __webpack_require__(4070) - -var root = convert('root') -var element = convert('element') -var text = convert('text') - -module.exports = wrapper - -function wrapper(h, node, options) { - var settings = options || {} - var r = react(h) - var v = vue(h) - var vd = vdom(h) - var prefix - - if (typeof h !== 'function') { - throw new Error('h is not a function') - } - - if (typeof settings === 'string' || typeof settings === 'boolean') { - prefix = settings - settings = {} - } else { - prefix = settings.prefix - } - - if (root(node)) { - node = - node.children.length === 1 && element(node.children[0]) - ? node.children[0] - : { - type: 'element', - tagName: 'div', - properties: {}, - children: node.children - } - } else if (!element(node)) { - throw new Error( - 'Expected root or element, not `' + ((node && node.type) || node) + '`' - ) - } - - return toH(h, node, { - schema: settings.space === 'svg' ? svg : html, - prefix: prefix == null ? (r || v || vd ? 'h-' : null) : prefix, - key: 0, - react: r, - vue: v, - vdom: vd, - hyperscript: hyperscript(h) - }) -} - -// Transform a hast node through a hyperscript interface to *anything*! -function toH(h, node, ctx) { - var parentSchema = ctx.schema - var schema = parentSchema - var name = node.tagName - var attributes = {} - var nodes = [] - var index = -1 - var key - var value - - if (parentSchema.space === 'html' && name.toLowerCase() === 'svg') { - schema = svg - ctx.schema = schema - } - - for (key in node.properties) { - addAttribute(attributes, key, node.properties[key], ctx, name) - } - - if (ctx.vdom) { - if (schema.space === 'html') { - name = name.toUpperCase() - } else { - attributes.namespace = ns[schema.space] - } - } - if (ctx.prefix) { - ctx.key++ - attributes.key = ctx.prefix + ctx.key - } + // eslint-disable-next-line functional/prefer-readonly-type + function shuffle(array) { + let c = array.length - 1 // eslint-disable-line functional/no-let + // eslint-disable-next-line functional/no-loop-statement + for (c; c > 0; c--) { + const b = Math.floor(Math.random() * (c + 1)) + const a = array[c] + array[c] = array[b] // eslint-disable-line functional/immutable-data, no-param-reassign + array[b] = a // eslint-disable-line functional/immutable-data, no-param-reassign + } + return array + } + function addMethods(base, methods) { + if (!methods) { + return base + } + Object.keys(methods).forEach((key) => { + // eslint-disable-next-line functional/immutable-data, no-param-reassign + base[key] = methods[key](base) + }) + return base + } + function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0 + return format.replace(/%s/g, () => encodeURIComponent(args[i++])) + } - if (node.children) { - while (++index < node.children.length) { - value = node.children[index] + const version = '4.8.3' - if (element(value)) { - nodes.push(toH(h, value, ctx)) - } else if (text(value)) { - nodes.push(value.value) + const destroy = (base) => { + return () => { + return base.transporter.requester.destroy() + } } - } - } - - // Restore parent schema. - ctx.schema = parentSchema - - // Ensure no React warnings are triggered for void elements having children - // passed in. - return nodes.length - ? h.call(node, name, attributes, nodes) - : h.call(node, name, attributes) -} - -function addAttribute(props, prop, value, ctx, name) { - var info = find(ctx.schema, prop) - var subprop - - // Ignore nullish and `NaN` values. - // Ignore `false` and falsey known booleans for hyperlike DSLs. - if ( - value == null || - value !== value || - (value === false && (ctx.vue || ctx.vdom || ctx.hyperscript)) || - (!value && info.boolean && (ctx.vue || ctx.vdom || ctx.hyperscript)) - ) { - return - } - - if (value && typeof value === 'object' && 'length' in value) { - // Accept `array`. - // Most props are space-separated. - value = (info.commaSeparated ? commas : spaces).stringify(value) - } - - // Treat `true` and truthy known booleans. - if (info.boolean && ctx.hyperscript) { - value = '' - } - - // VDOM, Vue, and React accept `style` as object. - if ( - info.property === 'style' && - typeof value === 'string' && - (ctx.react || ctx.vue || ctx.vdom) - ) { - value = parseStyle(value, name) - } - - if (ctx.vue) { - if (info.property !== 'style') subprop = 'attrs' - } else if (!info.mustUseProperty) { - if (ctx.vdom) { - if (info.property !== 'style') subprop = 'attributes' - } else if (ctx.hyperscript) { - subprop = 'attrs' - } - } - - if (subprop) { - if (!props[subprop]) props[subprop] = {} - props[subprop][info.attribute] = value - } else if (info.space && ctx.react) { - props[hastToReact[info.property] || info.property] = value - } else { - props[info.attribute] = value - } -} - -// Check if `h` is `react.createElement`. -function react(h) { - var node = h && h('div') - return Boolean( - node && ('_owner' in node || '_store' in node) && node.key == null - ) -} - -// Check if `h` is `hyperscript`. -function hyperscript(h) { - return Boolean(h && h.context && h.cleanup) -} - -// Check if `h` is `virtual-dom/h`. -function vdom(h) { - return h && h('div').type === 'VirtualNode' -} - -function vue(h) { - var node = h && h('div') - return Boolean(node && node.context && node.context._isVue) -} - -function parseStyle(value, tagName) { - var result = {} - - try { - style(value, iterator) - } catch (error) { - error.message = - tagName + '[style]' + error.message.slice('undefined'.length) - throw error - } - - return result - - function iterator(name, value) { - if (name.slice(0, 4) === '-ms-') name = 'ms-' + name.slice(4) - result[name.replace(/-([a-z])/g, styleReplacer)] = value - } -} - -function styleReplacer($0, $1) { - return $1.toUpperCase() -} - - -/***/ }), - -/***/ 8849: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var s = __webpack_require__(3413) -var h = __webpack_require__(7156) -var find = __webpack_require__(3657) -var html = __webpack_require__(9515) -var svg = __webpack_require__(4589) -var vfileLocation = __webpack_require__(2403) -var ns = __webpack_require__(4992) - -module.exports = wrapper - -var own = {}.hasOwnProperty - -// Handlers. -var map = { - '#document': root, - '#document-fragment': root, - '#text': text, - '#comment': comment, - '#documentType': doctype -} - -// Wrapper to normalise options. -function wrapper(ast, options) { - var settings = options || {} - var file - - if (settings.messages) { - file = settings - settings = {} - } else { - file = settings.file - } - - return transform(ast, { - schema: settings.space === 'svg' ? svg : html, - file: file, - verbose: settings.verbose - }) -} - -// Transform a node. -function transform(ast, config) { - var schema = config.schema - var fn = own.call(map, ast.nodeName) ? map[ast.nodeName] : element - var children - var result - var position - - if (fn === element) { - config.schema = ast.namespaceURI === ns.svg ? svg : html - } - - if (ast.childNodes) { - children = nodes(ast.childNodes, config) - } - - result = fn(ast, children, config) - - if (ast.sourceCodeLocation && config.file) { - position = location(result, ast.sourceCodeLocation, config) - - if (position) { - config.location = true - result.position = position - } - } - - config.schema = schema - - return result -} - -// Transform children. -function nodes(children, config) { - var index = -1 - var result = [] - - while (++index < children.length) { - result[index] = transform(children[index], config) - } - - return result -} - -// Transform a document. -// Stores `ast.quirksMode` in `node.data.quirksMode`. -function root(ast, children, config) { - var result = { - type: 'root', - children: children, - data: {quirksMode: ast.mode === 'quirks' || ast.mode === 'limited-quirks'} - } - var doc - var location - - if (config.file && config.location) { - doc = String(config.file) - location = vfileLocation(doc) - result.position = { - start: location.toPoint(0), - end: location.toPoint(doc.length) - } - } - - return result -} - -// Transform a doctype. -function doctype(ast) { - return { - type: 'doctype', - name: ast.name || '', - public: ast.publicId || null, - system: ast.systemId || null - } -} - -// Transform a text. -function text(ast) { - return {type: 'text', value: ast.value} -} - -// Transform a comment. -function comment(ast) { - return {type: 'comment', value: ast.data} -} - -// Transform an element. -function element(ast, children, config) { - var fn = config.schema.space === 'svg' ? s : h - var props = {} - var index = -1 - var result - var attribute - var pos - var start - var end - - while (++index < ast.attrs.length) { - attribute = ast.attrs[index] - props[(attribute.prefix ? attribute.prefix + ':' : '') + attribute.name] = - attribute.value - } - - result = fn(ast.tagName, props, children) - - if (result.tagName === 'template' && 'content' in ast) { - pos = ast.sourceCodeLocation - start = pos && pos.startTag && position(pos.startTag).end - end = pos && pos.endTag && position(pos.endTag).start - - result.content = transform(ast.content, config) - - if ((start || end) && config.file) { - result.content.position = {start: start, end: end} - } - } - return result -} + const AuthMode = { + /** + * If auth credentials should be in query parameters. + */ + WithinQueryParameters: 0, + /** + * If auth credentials should be in headers. + */ + WithinHeaders: 1 + } -// Create clean positional information. -function location(node, location, config) { - var result = position(location) - var tail - var key - var props + exports.AuthMode = AuthMode + exports.addMethods = addMethods + exports.createAuth = createAuth + exports.createRetryablePromise = createRetryablePromise + exports.createWaitablePromise = createWaitablePromise + exports.destroy = destroy + exports.encode = encode + exports.shuffle = shuffle + exports.version = version + + /***/ + }, - if (node.type === 'element') { - tail = node.children[node.children.length - 1] + /***/ 1905: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(5526) - // Bug for unclosed with children. - // See: . - if (!location.endTag && tail && tail.position && tail.position.end) { - result.end = Object.assign({}, tail.position.end) - } + /***/ + }, - if (config.verbose) { - props = {} + /***/ 1557: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + var clientCommon = __webpack_require__(1905) + var transporter = __webpack_require__(2424) + var requesterCommon = __webpack_require__(6373) + + const createRecommendationClient = (options) => { + const region = options.region || 'us' + const auth = clientCommon.createAuth( + clientCommon.AuthMode.WithinHeaders, + options.appId, + options.apiKey + ) + const transporter$1 = transporter.createTransporter({ + hosts: [{ url: `recommendation.${region}.algolia.com` }], + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/json' }, + ...options.headers + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters + } + }) + return clientCommon.addMethods( + { appId: options.appId, transporter: transporter$1 }, + options.methods + ) + } - for (key in location.attrs) { - props[find(config.schema, key).property] = position(location.attrs[key]) + const getPersonalizationStrategy = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/strategies/personalization' + }, + requestOptions + ) + } } - node.data = { - position: { - opening: position(location.startTag), - closing: location.endTag ? position(location.endTag) : null, - properties: props + const setPersonalizationStrategy = (base) => { + return (personalizationStrategy, requestOptions) => { + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: '1/strategies/personalization', + data: personalizationStrategy + }, + requestOptions + ) } } - } - } - return result -} + exports.createRecommendationClient = createRecommendationClient + exports.getPersonalizationStrategy = getPersonalizationStrategy + exports.setPersonalizationStrategy = setPersonalizationStrategy -function position(loc) { - var start = point({ - line: loc.startLine, - column: loc.startCol, - offset: loc.startOffset - }) - var end = point({ - line: loc.endLine, - column: loc.endCol, - offset: loc.endOffset - }) - return start || end ? {start: start, end: end} : null -} + /***/ + }, -function point(point) { - return point.line && point.column ? point : null -} + /***/ 31: /***/ (module, __unused_webpack_exports, __webpack_require__) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(1557) + /***/ + }, -/***/ }), + /***/ 102: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + var clientCommon = __webpack_require__(1905) + var transporter = __webpack_require__(2424) + var requesterCommon = __webpack_require__(6373) + var crypto = __webpack_require__(6417) + + function createBrowsablePromise(options) { + const browse = (data) => { + return options.request(data).then((response) => { + /** + * First we send to the developer the + * batch retrieved from the API. + */ + if (options.batch !== undefined) { + options.batch(response.hits) + } + /** + * Then, we ask to the browse concrete implementation + * if we should stop browsing. As example, the `browseObjects` + * method will stop if the cursor is not present on the response. + */ + if (options.shouldStop(response)) { + return undefined + } + /** + * Finally, if the response contains a cursor, we browse to the next + * batch using that same cursor. Otherwise, we just use the traditional + * browsing using the page element. + */ + if (response.cursor) { + return browse({ + cursor: response.cursor + }) + } + return browse({ + page: (data.page || 0) + 1 + }) + }) + } + return browse({}) + } -/***/ 5253: -/***/ ((module) => { + const createSearchClient = (options) => { + const appId = options.appId + const auth = clientCommon.createAuth( + options.authMode !== undefined + ? options.authMode + : clientCommon.AuthMode.WithinHeaders, + appId, + options.apiKey + ) + const transporter$1 = transporter.createTransporter({ + hosts: [ + { + url: `${appId}-dsn.algolia.net`, + accept: transporter.CallEnum.Read + }, + { url: `${appId}.algolia.net`, accept: transporter.CallEnum.Write } + ].concat( + clientCommon.shuffle([ + { url: `${appId}-1.algolianet.com` }, + { url: `${appId}-2.algolianet.com` }, + { url: `${appId}-3.algolianet.com` } + ]) + ), + ...options, + headers: { + ...auth.headers(), + ...{ 'content-type': 'application/x-www-form-urlencoded' }, + ...options.headers + }, + queryParameters: { + ...auth.queryParameters(), + ...options.queryParameters + } + }) + const base = { + transporter: transporter$1, + appId, + addAlgoliaAgent(segment, version) { + transporter$1.userAgent.add({ segment, version }) + }, + clearCache() { + return Promise.all([ + transporter$1.requestsCache.clear(), + transporter$1.responsesCache.clear() + ]).then(() => undefined) + } + } + return clientCommon.addMethods(base, options.methods) + } -"use strict"; + function createMissingObjectIDError() { + return { + name: 'MissingObjectIDError', + message: + 'All objects must have an unique objectID ' + + '(like a primary key) to be valid. ' + + 'Algolia is also able to generate objectIDs ' + + "automatically but *it's not recommended*. " + + "To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option." + } + } + function createObjectNotFoundError() { + return { + name: 'ObjectNotFoundError', + message: 'Object not found.' + } + } -module.exports = parse + function createValidUntilNotFoundError() { + return { + name: 'ValidUntilNotFoundError', + message: 'ValidUntil not found in given secured api key.' + } + } + + const addApiKey = (base) => { + return (acl, requestOptions) => { + const { queryParameters, ...options } = requestOptions || {} + const data = { + acl, + ...(queryParameters !== undefined ? { queryParameters } : {}) + } + const wait = (response, waitRequestOptions) => { + return clientCommon.createRetryablePromise((retry) => { + return getApiKey(base)(response.key, waitRequestOptions).catch( + (apiError) => { + if (apiError.status !== 404) { + throw apiError + } + return retry() + } + ) + }) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: '1/keys', + data + }, + options + ), + wait + ) + } + } + + const assignUserID = (base) => { + return (userID, clusterName, requestOptions) => { + const mappedRequestOptions = transporter.createMappedRequestOptions( + requestOptions + ) + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: '1/clusters/mapping', + data: { cluster: clusterName } + }, + mappedRequestOptions + ) + } + } + + const assignUserIDs = (base) => { + return (userIDs, clusterName, requestOptions) => { + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: '1/clusters/mapping/batch', + data: { + users: userIDs, + cluster: clusterName + } + }, + requestOptions + ) + } + } + + const copyIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask } + }).waitTask(response.taskID, waitRequestOptions) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/operation', from), + data: { + operation: 'copy', + destination: to + } + }, + requestOptions + ), + wait + ) + } + } + + const copyRules = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Rules] + }) + } + } + + const copySettings = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Settings] + }) + } + } + + const copySynonyms = (base) => { + return (from, to, requestOptions) => { + return copyIndex(base)(from, to, { + ...requestOptions, + scope: [ScopeEnum.Synonyms] + }) + } + } + + const deleteApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return clientCommon.createRetryablePromise((retry) => { + return getApiKey(base)(apiKey, waitRequestOptions) + .then(retry) + .catch((apiError) => { + if (apiError.status !== 404) { + throw apiError + } + }) + }) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('1/keys/%s', apiKey) + }, + requestOptions + ), + wait + ) + } + } + + const generateSecuredApiKey = () => { + return (parentApiKey, restrictions) => { + const queryParameters = transporter.serializeQueryParameters( + restrictions + ) + const securedKey = crypto + .createHmac('sha256', parentApiKey) + .update(queryParameters) + .digest('hex') + return Buffer.from(securedKey + queryParameters).toString('base64') + } + } + + const getApiKey = (base) => { + return (apiKey, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/keys/%s', apiKey) + }, + requestOptions + ) + } + } + + const getLogs = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/logs' + }, + requestOptions + ) + } + } + + const getSecuredApiKeyRemainingValidity = () => { + return (securedApiKey) => { + const decodedString = Buffer.from(securedApiKey, 'base64').toString( + 'ascii' + ) + const regex = /validUntil=(\d+)/ + const match = decodedString.match(regex) + if (match === null) { + throw createValidUntilNotFoundError() + } + return ( + parseInt(match[1], 10) - Math.round(new Date().getTime() / 1000) + ) + } + } + + const getTopUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/clusters/mapping/top' + }, + requestOptions + ) + } + } + + const getUserID = (base) => { + return (userID, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode('1/clusters/mapping/%s', userID) + }, + requestOptions + ) + } + } + + const hasPendingMappings = (base) => { + return (requestOptions) => { + const { retrieveMappings, ...options } = requestOptions || {} + if (retrieveMappings === true) { + // eslint-disable-next-line functional/immutable-data + options.getClusters = true + } + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/clusters/mapping/pending' + }, + options + ) + } + } + + const initIndex = (base) => { + return (indexName, options = {}) => { + const searchIndex = { + transporter: base.transporter, + appId: base.appId, + indexName + } + return clientCommon.addMethods(searchIndex, options.methods) + } + } + + const listApiKeys = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/keys' + }, + requestOptions + ) + } + } + + const listClusters = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/clusters' + }, + requestOptions + ) + } + } + + const listIndices = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/indexes' + }, + requestOptions + ) + } + } + + const listUserIDs = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: '1/clusters/mapping' + }, + requestOptions + ) + } + } + + const moveIndex = (base) => { + return (from, to, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return initIndex(base)(from, { + methods: { waitTask } + }).waitTask(response.taskID, waitRequestOptions) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/operation', from), + data: { + operation: 'move', + destination: to + } + }, + requestOptions + ), + wait + ) + } + } + + const multipleBatch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return Promise.all( + Object.keys(response.taskID).map((indexName) => { + return initIndex(base)(indexName, { + methods: { waitTask } + }).waitTask(response.taskID[indexName], waitRequestOptions) + }) + ) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/batch', + data: { + requests + } + }, + requestOptions + ), + wait + ) + } + } + + const multipleGetObjects = (base) => { + return (requests, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests + } + }, + requestOptions + ) + } + } + + const multipleQueries = (base) => { + return (queries, requestOptions) => { + const requests = queries.map((query) => { + return { + ...query, + params: transporter.serializeQueryParameters(query.params || {}) + } + }) + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/queries', + data: { + requests + }, + cacheable: true + }, + requestOptions + ) + } + } + + const multipleSearchForFacetValues = (base) => { + return (queries, requestOptions) => { + return Promise.all( + queries.map((query) => { + const { facetName, facetQuery, ...params } = query.params + return initIndex(base)(query.indexName, { + methods: { searchForFacetValues } + }).searchForFacetValues(facetName, facetQuery, { + ...requestOptions, + ...params + }) + }) + ) + } + } + + const removeUserID = (base) => { + return (userID, requestOptions) => { + const mappedRequestOptions = transporter.createMappedRequestOptions( + requestOptions + ) + // eslint-disable-next-line functional/immutable-data + mappedRequestOptions.queryParameters['X-Algolia-User-ID'] = userID + return base.transporter.write( + { + method: requesterCommon.MethodEnum.Delete, + path: '1/clusters/mapping' + }, + mappedRequestOptions + ) + } + } + + const restoreApiKey = (base) => { + return (apiKey, requestOptions) => { + const wait = (_, waitRequestOptions) => { + return clientCommon.createRetryablePromise((retry) => { + return getApiKey(base)(apiKey, waitRequestOptions).catch( + (apiError) => { + if (apiError.status !== 404) { + throw apiError + } + return retry() + } + ) + }) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/keys/%s/restore', apiKey) + }, + requestOptions + ), + wait + ) + } + } + + const searchUserIDs = (base) => { + return (query, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: '1/clusters/mapping/search', + data: { + query + } + }, + requestOptions + ) + } + } + + const updateApiKey = (base) => { + return (apiKey, requestOptions) => { + const updatedFields = Object.assign({}, requestOptions) + const { queryParameters, ...options } = requestOptions || {} + const data = queryParameters ? { queryParameters } : {} + const apiKeyFields = [ + 'acl', + 'indexes', + 'referers', + 'restrictSources', + 'queryParameters', + 'description', + 'maxQueriesPerIPPerHour', + 'maxHitsPerQuery' + ] + const hasChanged = (getApiKeyResponse) => { + return Object.keys(updatedFields) + .filter( + (updatedField) => apiKeyFields.indexOf(updatedField) !== -1 + ) + .every((updatedField) => { + return ( + getApiKeyResponse[updatedField] === + updatedFields[updatedField] + ) + }) + } + const wait = (_, waitRequestOptions) => + clientCommon.createRetryablePromise((retry) => { + return getApiKey(base)(apiKey, waitRequestOptions).then( + (getApiKeyResponse) => { + return hasChanged(getApiKeyResponse) + ? Promise.resolve() + : retry() + } + ) + }) + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Put, + path: clientCommon.encode('1/keys/%s', apiKey), + data + }, + options + ), + wait + ) + } + } + + const batch = (base) => { + return (requests, requestOptions) => { + const wait = (response, waitRequestOptions) => { + return waitTask(base)(response.taskID, waitRequestOptions) + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/batch', base.indexName), + data: { + requests + } + }, + requestOptions + ), + wait + ) + } + } + + const browseObjects = (base) => { + return (requestOptions) => { + return createBrowsablePromise({ + shouldStop: (response) => response.cursor === undefined, + ...requestOptions, + request: (data) => + base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/browse', + base.indexName + ), + data + }, + requestOptions + ) + }) + } + } + + const browseRules = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions + } + return createBrowsablePromise({ + shouldStop: (response) => + response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchRules(base)('', { ...options, ...data }).then( + (response) => { + return { + ...response, + hits: response.hits.map((rule) => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete rule._highlightResult + return rule + }) + } + } + ) + } + }) + } + } + + const browseSynonyms = (base) => { + return (requestOptions) => { + const options = { + hitsPerPage: 1000, + ...requestOptions + } + return createBrowsablePromise({ + shouldStop: (response) => + response.hits.length < options.hitsPerPage, + ...options, + request(data) { + return searchSynonyms(base)('', { ...options, ...data }).then( + (response) => { + return { + ...response, + hits: response.hits.map((synonym) => { + // eslint-disable-next-line functional/immutable-data,no-param-reassign + delete synonym._highlightResult + return synonym + }) + } + } + ) + } + }) + } + } + + const chunkedBatch = (base) => { + return (bodies, action, requestOptions) => { + const { batchSize, ...options } = requestOptions || {} + const response = { + taskIDs: [], + objectIDs: [] + } + const forEachBatch = (lastIndex = 0) => { + // eslint-disable-next-line functional/prefer-readonly-type + const bodiesChunk = [] + // eslint-disable-next-line functional/no-let + let index + /* eslint-disable-next-line functional/no-loop-statement */ + for (index = lastIndex; index < bodies.length; index++) { + // eslint-disable-next-line functional/immutable-data + bodiesChunk.push(bodies[index]) + if (bodiesChunk.length === (batchSize || 1000)) { + break + } + } + if (bodiesChunk.length === 0) { + return Promise.resolve(response) + } + return batch(base)( + bodiesChunk.map((body) => { + return { + action, + body + } + }), + options + ).then((res) => { + response.objectIDs = response.objectIDs.concat(res.objectIDs) // eslint-disable-line functional/immutable-data + response.taskIDs.push(res.taskID) // eslint-disable-line functional/immutable-data + index++ + return forEachBatch(index) + }) + } + return clientCommon.createWaitablePromise( + forEachBatch(), + (chunkedBatchResponse, waitRequestOptions) => { + return Promise.all( + chunkedBatchResponse.taskIDs.map((taskID) => { + return waitTask(base)(taskID, waitRequestOptions) + }) + ) + } + ) + } + } + + const clearObjects = (base) => { + return (requestOptions) => { + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/clear', base.indexName) + }, + requestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const clearRules = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/rules/clear', + base.indexName + ) + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const clearSynonyms = (base) => { + return (requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/synonyms/clear', + base.indexName + ) + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const deleteBy = (base) => { + return (filters, requestOptions) => { + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/deleteByQuery', + base.indexName + ), + data: filters + }, + requestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const deleteIndex = (base) => { + return (requestOptions) => { + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode('1/indexes/%s', base.indexName) + }, + requestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const deleteObject = (base) => { + return (objectID, requestOptions) => { + return clientCommon.createWaitablePromise( + deleteObjects(base)([objectID], requestOptions).then((response) => { + return { taskID: response.taskIDs[0] } + }), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const deleteObjects = (base) => { + return (objectIDs, requestOptions) => { + const objects = objectIDs.map((objectID) => { + return { objectID } + }) + return chunkedBatch(base)( + objects, + BatchActionEnum.DeleteObject, + requestOptions + ) + } + } + + const deleteRule = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode( + '1/indexes/%s/rules/%s', + base.indexName, + objectID + ) + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const deleteSynonym = (base) => { + return (objectID, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Delete, + path: clientCommon.encode( + '1/indexes/%s/synonyms/%s', + base.indexName, + objectID + ) + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const exists = (base) => { + return (requestOptions) => { + return getSettings(base)(requestOptions) + .then(() => true) + .catch((error) => { + if (error.status !== 404) { + throw error + } + return false + }) + } + } + + const findAnswers = (base) => { + return (query, queryLanguages, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/answers/%s/prediction', + base.indexName + ), + data: { + query, + queryLanguages + }, + cacheable: true + }, + requestOptions + ) + } + } + + const findObject = (base) => { + return (callback, requestOptions) => { + const { query, paginate, ...options } = requestOptions || {} + // eslint-disable-next-line functional/no-let + let page = 0 + const forEachPage = () => { + return search(base)(query || '', { ...options, page }).then( + (result) => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(result.hits)) { + // eslint-disable-next-line promise/no-callback-in-promise + if (callback(hit)) { + return { + object: hit, + position: parseInt(position, 10), + page + } + } + } + page++ + // paginate if option was set and has next page + if (paginate === false || page >= result.nbPages) { + throw createObjectNotFoundError() + } + return forEachPage() + } + ) + } + return forEachPage() + } + } + + const getObject = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode( + '1/indexes/%s/%s', + base.indexName, + objectID + ) + }, + requestOptions + ) + } + } + + const getObjectPosition = () => { + return (searchResponse, objectID) => { + // eslint-disable-next-line functional/no-loop-statement + for (const [position, hit] of Object.entries(searchResponse.hits)) { + if (hit.objectID === objectID) { + return parseInt(position, 10) + } + } + return -1 + } + } + + const getObjects = (base) => { + return (objectIDs, requestOptions) => { + const { attributesToRetrieve, ...options } = requestOptions || {} + const requests = objectIDs.map((objectID) => { + return { + indexName: base.indexName, + objectID, + ...(attributesToRetrieve ? { attributesToRetrieve } : {}) + } + }) + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: '1/indexes/*/objects', + data: { + requests + } + }, + options + ) + } + } + + const getRule = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode( + '1/indexes/%s/rules/%s', + base.indexName, + objectID + ) + }, + requestOptions + ) + } + } + + const getSettings = (base) => { + return (requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode( + '1/indexes/%s/settings', + base.indexName + ), + data: { + getVersion: 2 + } + }, + requestOptions + ) + } + } + + const getSynonym = (base) => { + return (objectID, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode( + `1/indexes/%s/synonyms/%s`, + base.indexName, + objectID + ) + }, + requestOptions + ) + } + } + + const getTask = (base) => { + return (taskID, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Get, + path: clientCommon.encode( + '1/indexes/%s/task/%s', + base.indexName, + taskID.toString() + ) + }, + requestOptions + ) + } + } + + const partialUpdateObject = (base) => { + return (object, requestOptions) => { + return clientCommon.createWaitablePromise( + partialUpdateObjects(base)([object], requestOptions).then( + (response) => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0] + } + } + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const partialUpdateObjects = (base) => { + return (objects, requestOptions) => { + const { createIfNotExists, ...options } = requestOptions || {} + const action = createIfNotExists + ? BatchActionEnum.PartialUpdateObject + : BatchActionEnum.PartialUpdateObjectNoCreate + return chunkedBatch(base)(objects, action, options) + } + } + + const replaceAllObjects = (base) => { + return (objects, requestOptions) => { + const { + safe, + autoGenerateObjectIDIfNotExist, + batchSize, + ...options + } = requestOptions || {} + const operation = (from, to, type, operationRequestOptions) => { + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/operation', from), + data: { + operation: type, + destination: to + } + }, + operationRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + const randomSuffix = Math.random().toString(36).substring(7) + const temporaryIndexName = `${base.indexName}_tmp_${randomSuffix}` + const saveObjectsInTemporary = saveObjects({ + appId: base.appId, + transporter: base.transporter, + indexName: temporaryIndexName + }) + // @ts-ignore + // eslint-disable-next-line prefer-const, functional/no-let, functional/prefer-readonly-type + let responses = [] + const copyWaitablePromise = operation( + base.indexName, + temporaryIndexName, + 'copy', + { + ...options, + scope: ['settings', 'synonyms', 'rules'] + } + ) + // eslint-disable-next-line functional/immutable-data + responses.push(copyWaitablePromise) + const result = (safe + ? copyWaitablePromise.wait(options) + : copyWaitablePromise + ) + .then(() => { + const saveObjectsWaitablePromise = saveObjectsInTemporary( + objects, + { + ...options, + autoGenerateObjectIDIfNotExist, + batchSize + } + ) + // eslint-disable-next-line functional/immutable-data + responses.push(saveObjectsWaitablePromise) + return safe + ? saveObjectsWaitablePromise.wait(options) + : saveObjectsWaitablePromise + }) + .then(() => { + const moveWaitablePromise = operation( + temporaryIndexName, + base.indexName, + 'move', + options + ) + // eslint-disable-next-line functional/immutable-data + responses.push(moveWaitablePromise) + return safe + ? moveWaitablePromise.wait(options) + : moveWaitablePromise + }) + .then(() => Promise.all(responses)) + .then(([copyResponse, saveObjectsResponse, moveResponse]) => { + return { + objectIDs: saveObjectsResponse.objectIDs, + taskIDs: [ + copyResponse.taskID, + ...saveObjectsResponse.taskIDs, + moveResponse.taskID + ] + } + }) + return clientCommon.createWaitablePromise( + result, + (_, waitRequestOptions) => { + return Promise.all( + responses.map((response) => response.wait(waitRequestOptions)) + ) + } + ) + } + } + + const replaceAllRules = (base) => { + return (rules, requestOptions) => { + return saveRules(base)(rules, { + ...requestOptions, + clearExistingRules: true + }) + } + } + + const replaceAllSynonyms = (base) => { + return (synonyms, requestOptions) => { + return saveSynonyms(base)(synonyms, { + ...requestOptions, + clearExistingSynonyms: true + }) + } + } + + const saveObject = (base) => { + return (object, requestOptions) => { + return clientCommon.createWaitablePromise( + saveObjects(base)([object], requestOptions).then((response) => { + return { + objectID: response.objectIDs[0], + taskID: response.taskIDs[0] + } + }), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const saveObjects = (base) => { + return (objects, requestOptions) => { + const { autoGenerateObjectIDIfNotExist, ...options } = + requestOptions || {} + const action = autoGenerateObjectIDIfNotExist + ? BatchActionEnum.AddObject + : BatchActionEnum.UpdateObject + if (action === BatchActionEnum.UpdateObject) { + // eslint-disable-next-line functional/no-loop-statement + for (const object of objects) { + if (object.objectID === undefined) { + return clientCommon.createWaitablePromise( + Promise.reject(createMissingObjectIDError()) + ) + } + } + } + return chunkedBatch(base)(objects, action, options) + } + } + + const saveRule = (base) => { + return (rule, requestOptions) => { + return saveRules(base)([rule], requestOptions) + } + } + + const saveRules = (base) => { + return (rules, requestOptions) => { + const { forwardToReplicas, clearExistingRules, ...options } = + requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + if (clearExistingRules) { + mappedRequestOptions.queryParameters.clearExistingRules = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/rules/batch', + base.indexName + ), + data: rules + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const saveSynonym = (base) => { + return (synonym, requestOptions) => { + return saveSynonyms(base)([synonym], requestOptions) + } + } + + const saveSynonyms = (base) => { + return (synonyms, requestOptions) => { + const { + forwardToReplicas, + clearExistingSynonyms, + replaceExistingSynonyms, + ...options + } = requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + if (replaceExistingSynonyms || clearExistingSynonyms) { + mappedRequestOptions.queryParameters.replaceExistingSynonyms = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/synonyms/batch', + base.indexName + ), + data: synonyms + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const search = (base) => { + return (query, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode('1/indexes/%s/query', base.indexName), + data: { + query + }, + cacheable: true + }, + requestOptions + ) + } + } + + const searchForFacetValues = (base) => { + return (facetName, facetQuery, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/facets/%s/query', + base.indexName, + facetName + ), + data: { + facetQuery + }, + cacheable: true + }, + requestOptions + ) + } + } + + const searchRules = (base) => { + return (query, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/rules/search', + base.indexName + ), + data: { + query + } + }, + requestOptions + ) + } + } + + const searchSynonyms = (base) => { + return (query, requestOptions) => { + return base.transporter.read( + { + method: requesterCommon.MethodEnum.Post, + path: clientCommon.encode( + '1/indexes/%s/synonyms/search', + base.indexName + ), + data: { + query + } + }, + requestOptions + ) + } + } + + const setSettings = (base) => { + return (settings, requestOptions) => { + const { forwardToReplicas, ...options } = requestOptions || {} + const mappedRequestOptions = transporter.createMappedRequestOptions( + options + ) + if (forwardToReplicas) { + mappedRequestOptions.queryParameters.forwardToReplicas = 1 // eslint-disable-line functional/immutable-data + } + return clientCommon.createWaitablePromise( + base.transporter.write( + { + method: requesterCommon.MethodEnum.Put, + path: clientCommon.encode( + '1/indexes/%s/settings', + base.indexName + ), + data: settings + }, + mappedRequestOptions + ), + (response, waitRequestOptions) => + waitTask(base)(response.taskID, waitRequestOptions) + ) + } + } + + const waitTask = (base) => { + return (taskID, requestOptions) => { + return clientCommon.createRetryablePromise((retry) => { + return getTask(base)(taskID, requestOptions).then((response) => { + return response.status !== 'published' ? retry() : undefined + }) + }) + } + } + + const ApiKeyACLEnum = { + AddObject: 'addObject', + Analytics: 'analytics', + Browser: 'browse', + DeleteIndex: 'deleteIndex', + DeleteObject: 'deleteObject', + EditSettings: 'editSettings', + ListIndexes: 'listIndexes', + Logs: 'logs', + Recommendation: 'recommendation', + Search: 'search', + SeeUnretrievableAttributes: 'seeUnretrievableAttributes', + Settings: 'settings', + Usage: 'usage' + } + + const BatchActionEnum = { + AddObject: 'addObject', + UpdateObject: 'updateObject', + PartialUpdateObject: 'partialUpdateObject', + PartialUpdateObjectNoCreate: 'partialUpdateObjectNoCreate', + DeleteObject: 'deleteObject', + DeleteIndex: 'delete', + ClearIndex: 'clear' + } + + const ScopeEnum = { + Settings: 'settings', + Synonyms: 'synonyms', + Rules: 'rules' + } + + const StrategyEnum = { + None: 'none', + StopIfEnoughMatches: 'stopIfEnoughMatches' + } + + const SynonymEnum = { + Synonym: 'synonym', + OneWaySynonym: 'oneWaySynonym', + AltCorrection1: 'altCorrection1', + AltCorrection2: 'altCorrection2', + Placeholder: 'placeholder' + } + + exports.ApiKeyACLEnum = ApiKeyACLEnum + exports.BatchActionEnum = BatchActionEnum + exports.ScopeEnum = ScopeEnum + exports.StrategyEnum = StrategyEnum + exports.SynonymEnum = SynonymEnum + exports.addApiKey = addApiKey + exports.assignUserID = assignUserID + exports.assignUserIDs = assignUserIDs + exports.batch = batch + exports.browseObjects = browseObjects + exports.browseRules = browseRules + exports.browseSynonyms = browseSynonyms + exports.chunkedBatch = chunkedBatch + exports.clearObjects = clearObjects + exports.clearRules = clearRules + exports.clearSynonyms = clearSynonyms + exports.copyIndex = copyIndex + exports.copyRules = copyRules + exports.copySettings = copySettings + exports.copySynonyms = copySynonyms + exports.createBrowsablePromise = createBrowsablePromise + exports.createMissingObjectIDError = createMissingObjectIDError + exports.createObjectNotFoundError = createObjectNotFoundError + exports.createSearchClient = createSearchClient + exports.createValidUntilNotFoundError = createValidUntilNotFoundError + exports.deleteApiKey = deleteApiKey + exports.deleteBy = deleteBy + exports.deleteIndex = deleteIndex + exports.deleteObject = deleteObject + exports.deleteObjects = deleteObjects + exports.deleteRule = deleteRule + exports.deleteSynonym = deleteSynonym + exports.exists = exists + exports.findAnswers = findAnswers + exports.findObject = findObject + exports.generateSecuredApiKey = generateSecuredApiKey + exports.getApiKey = getApiKey + exports.getLogs = getLogs + exports.getObject = getObject + exports.getObjectPosition = getObjectPosition + exports.getObjects = getObjects + exports.getRule = getRule + exports.getSecuredApiKeyRemainingValidity = getSecuredApiKeyRemainingValidity + exports.getSettings = getSettings + exports.getSynonym = getSynonym + exports.getTask = getTask + exports.getTopUserIDs = getTopUserIDs + exports.getUserID = getUserID + exports.hasPendingMappings = hasPendingMappings + exports.initIndex = initIndex + exports.listApiKeys = listApiKeys + exports.listClusters = listClusters + exports.listIndices = listIndices + exports.listUserIDs = listUserIDs + exports.moveIndex = moveIndex + exports.multipleBatch = multipleBatch + exports.multipleGetObjects = multipleGetObjects + exports.multipleQueries = multipleQueries + exports.multipleSearchForFacetValues = multipleSearchForFacetValues + exports.partialUpdateObject = partialUpdateObject + exports.partialUpdateObjects = partialUpdateObjects + exports.removeUserID = removeUserID + exports.replaceAllObjects = replaceAllObjects + exports.replaceAllRules = replaceAllRules + exports.replaceAllSynonyms = replaceAllSynonyms + exports.restoreApiKey = restoreApiKey + exports.saveObject = saveObject + exports.saveObjects = saveObjects + exports.saveRule = saveRule + exports.saveRules = saveRules + exports.saveSynonym = saveSynonym + exports.saveSynonyms = saveSynonyms + exports.search = search + exports.searchForFacetValues = searchForFacetValues + exports.searchRules = searchRules + exports.searchSynonyms = searchSynonyms + exports.searchUserIDs = searchUserIDs + exports.setSettings = setSettings + exports.updateApiKey = updateApiKey + exports.waitTask = waitTask + + /***/ + }, + + /***/ 2425: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(102) + + /***/ + }, + + /***/ 242: /***/ (__unused_webpack_module, exports) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + function createNullLogger() { + return { + debug(_message, _args) { + return Promise.resolve() + }, + info(_message, _args) { + return Promise.resolve() + }, + error(_message, _args) { + return Promise.resolve() + } + } + } + + const LogLevelEnum = { + Debug: 1, + Info: 2, + Error: 3 + } + + exports.LogLevelEnum = LogLevelEnum + exports.createNullLogger = createNullLogger + + /***/ + }, + + /***/ 3564: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(242) + + /***/ + }, + + /***/ 6721: /***/ (__unused_webpack_module, exports) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + const MethodEnum = { + Delete: 'DELETE', + Get: 'GET', + Post: 'POST', + Put: 'PUT' + } + + exports.MethodEnum = MethodEnum + + /***/ + }, + + /***/ 6373: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(6721) + + /***/ + }, + + /***/ 9437: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + var http = __webpack_require__(8605) + var https = __webpack_require__(7211) + var URL = __webpack_require__(8835) + + /* eslint functional/prefer-readonly-type: 0 */ + const agentOptions = { keepAlive: true } + const defaultHttpAgent = new http.Agent(agentOptions) + const defaultHttpsAgent = new https.Agent(agentOptions) + function createNodeHttpRequester({ + agent: userGlobalAgent, + httpAgent: userHttpAgent, + httpsAgent: userHttpsAgent, + requesterOptions = {} + } = {}) { + const httpAgent = userHttpAgent || userGlobalAgent || defaultHttpAgent + const httpsAgent = + userHttpsAgent || userGlobalAgent || defaultHttpsAgent + return { + send(request) { + return new Promise((resolve) => { + const url = URL.parse(request.url) + const path = + url.query === null + ? url.pathname + : `${url.pathname}?${url.query}` + const options = { + ...requesterOptions, + agent: url.protocol === 'https:' ? httpsAgent : httpAgent, + hostname: url.hostname, + path, + method: request.method, + headers: { + ...(requesterOptions && requesterOptions.headers + ? requesterOptions.headers + : {}), + ...request.headers + }, + ...(url.port !== undefined ? { port: url.port || '' } : {}) + } + const req = (url.protocol === 'https:' ? https : http).request( + options, + (response) => { + // eslint-disable-next-line functional/no-let + let contentBuffers = [] + response.on('data', (chunk) => { + contentBuffers = contentBuffers.concat(chunk) + }) + response.on('end', () => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(connectTimeout) + // eslint-disable-next-line @typescript-eslint/no-use-before-define + clearTimeout(responseTimeout) + resolve({ + status: response.statusCode || 0, + content: Buffer.concat(contentBuffers).toString(), + isTimedOut: false + }) + }) + } + ) + const createTimeout = (timeout, content) => { + return setTimeout(() => { + req.abort() + resolve({ + status: 0, + content, + isTimedOut: true + }) + }, timeout * 1000) + } + const connectTimeout = createTimeout( + request.connectTimeout, + 'Connection timeout' + ) + // eslint-disable-next-line functional/no-let + let responseTimeout + req.on('error', (error) => { + clearTimeout(connectTimeout) + clearTimeout(responseTimeout) + resolve({ + status: 0, + content: error.message, + isTimedOut: false + }) + }) + req.once('response', () => { + clearTimeout(connectTimeout) + responseTimeout = createTimeout( + request.responseTimeout, + 'Socket timeout' + ) + }) + if (request.data !== undefined) { + req.write(request.data) + } + req.end() + }) + }, + destroy() { + httpAgent.destroy() + httpsAgent.destroy() + return Promise.resolve() + } + } + } + + exports.createNodeHttpRequester = createNodeHttpRequester + + /***/ + }, + + /***/ 2724: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(9437) + + /***/ + }, + + /***/ 3056: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + Object.defineProperty(exports, '__esModule', { value: true }) + + var requesterCommon = __webpack_require__(6373) + + function createMappedRequestOptions(requestOptions, timeout) { + const options = requestOptions || {} + const data = options.data || {} + Object.keys(options).forEach((key) => { + if ( + [ + 'timeout', + 'headers', + 'queryParameters', + 'data', + 'cacheable' + ].indexOf(key) === -1 + ) { + data[key] = options[key] // eslint-disable-line functional/immutable-data + } + }) + return { + data: Object.entries(data).length > 0 ? data : undefined, + timeout: options.timeout || timeout, + headers: options.headers || {}, + queryParameters: options.queryParameters || {}, + cacheable: options.cacheable + } + } + + const CallEnum = { + /** + * If the host is read only. + */ + Read: 1, + /** + * If the host is write only. + */ + Write: 2, + /** + * If the host is both read and write. + */ + Any: 3 + } + + const HostStatusEnum = { + Up: 1, + Down: 2, + Timeouted: 3 + } + + // By default, API Clients at Algolia have expiration delay + // of 5 mins. In the JavaScript client, we have 2 mins. + const EXPIRATION_DELAY = 2 * 60 * 1000 + function createStatefulHost(host, status = HostStatusEnum.Up) { + return { + ...host, + status, + lastUpdate: Date.now() + } + } + function isStatefulHostUp(host) { + return ( + host.status === HostStatusEnum.Up || + Date.now() - host.lastUpdate > EXPIRATION_DELAY + ) + } + function isStatefulHostTimeouted(host) { + return ( + host.status === HostStatusEnum.Timeouted && + Date.now() - host.lastUpdate <= EXPIRATION_DELAY + ) + } + + function createStatelessHost(options) { + if (typeof options === 'string') { + return { + protocol: 'https', + url: options, + accept: CallEnum.Any + } + } + return { + protocol: options.protocol || 'https', + url: options.url, + accept: options.accept || CallEnum.Any + } + } + + function createRetryableOptions(hostsCache, statelessHosts) { + return Promise.all( + statelessHosts.map((statelessHost) => { + return hostsCache.get(statelessHost, () => { + return Promise.resolve(createStatefulHost(statelessHost)) + }) + }) + ).then((statefulHosts) => { + const hostsUp = statefulHosts.filter((host) => isStatefulHostUp(host)) + const hostsTimeouted = statefulHosts.filter((host) => + isStatefulHostTimeouted(host) + ) + /** + * Note, we put the hosts that previously timeouted on the end of the list. + */ + const hostsAvailable = [...hostsUp, ...hostsTimeouted] + const statelessHostsAvailable = + hostsAvailable.length > 0 + ? hostsAvailable.map((host) => createStatelessHost(host)) + : statelessHosts + return { + getTimeout(timeoutsCount, baseTimeout) { + /** + * Imagine that you have 4 hosts, if timeouts will increase + * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) + * + * Note that, the very next request, we start from the previous timeout + * + * 5 (timeouted) > 6 (timeouted) > 7 ... + * + * This strategy may need to be reviewed, but is the strategy on the our + * current v3 version. + */ + const timeoutMultiplier = + hostsTimeouted.length === 0 && timeoutsCount === 0 + ? 1 + : hostsTimeouted.length + 3 + timeoutsCount + return timeoutMultiplier * baseTimeout + }, + statelessHosts: statelessHostsAvailable + } + }) + } + + const isNetworkError = ({ isTimedOut, status }) => { + return !isTimedOut && ~~status === 0 + } + const isRetryable = (response) => { + const status = response.status + const isTimedOut = response.isTimedOut + return ( + isTimedOut || + isNetworkError(response) || + (~~(status / 100) !== 2 && ~~(status / 100) !== 4) + ) + } + const isSuccess = ({ status }) => { + return ~~(status / 100) === 2 + } + const retryDecision = (response, outcomes) => { + if (isRetryable(response)) { + return outcomes.onRetry(response) + } + if (isSuccess(response)) { + return outcomes.onSucess(response) + } + return outcomes.onFail(response) + } + + function retryableRequest( + transporter, + statelessHosts, + request, + requestOptions + ) { + const stackTrace = [] // eslint-disable-line functional/prefer-readonly-type + /** + * First we prepare the payload that do not depend from hosts. + */ + const data = serializeData(request, requestOptions) + const headers = serializeHeaders(transporter, requestOptions) + const method = request.method + // On `GET`, the data is proxied to query parameters. + const dataQueryParameters = + request.method !== requesterCommon.MethodEnum.Get + ? {} + : { + ...request.data, + ...requestOptions.data + } + const queryParameters = { + 'x-algolia-agent': transporter.userAgent.value, + ...transporter.queryParameters, + ...dataQueryParameters, + ...requestOptions.queryParameters + } + let timeoutsCount = 0 // eslint-disable-line functional/no-let + const retry = ( + hosts, // eslint-disable-line functional/prefer-readonly-type + getTimeout + ) => { + /** + * We iterate on each host, until there is no host left. + */ + const host = hosts.pop() // eslint-disable-line functional/immutable-data + if (host === undefined) { + throw createRetryError(stackTraceWithoutCredentials(stackTrace)) + } + const payload = { + data, + headers, + method, + url: serializeUrl(host, request.path, queryParameters), + connectTimeout: getTimeout( + timeoutsCount, + transporter.timeouts.connect + ), + responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout) + } + /** + * The stackFrame is pushed to the stackTrace so we + * can have information about onRetry and onFailure + * decisions. + */ + const pushToStackTrace = (response) => { + const stackFrame = { + request: payload, + response, + host, + triesLeft: hosts.length + } + // eslint-disable-next-line functional/immutable-data + stackTrace.push(stackFrame) + return stackFrame + } + const decisions = { + onSucess: (response) => deserializeSuccess(response), + onRetry(response) { + const stackFrame = pushToStackTrace(response) + /** + * If response is a timeout, we increaset the number of + * timeouts so we can increase the timeout later. + */ + if (response.isTimedOut) { + timeoutsCount++ + } + return Promise.all([ + /** + * Failures are individually send the logger, allowing + * the end user to debug / store stack frames even + * when a retry error does not happen. + */ + transporter.logger.info( + 'Retryable failure', + stackFrameWithoutCredentials(stackFrame) + ), + /** + * We also store the state of the host in failure cases. If the host, is + * down it will remain down for the next 2 minutes. In a timeout situation, + * this host will be added end of the list of hosts on the next request. + */ + transporter.hostsCache.set( + host, + createStatefulHost( + host, + response.isTimedOut + ? HostStatusEnum.Timeouted + : HostStatusEnum.Down + ) + ) + ]).then(() => retry(hosts, getTimeout)) + }, + onFail(response) { + pushToStackTrace(response) + throw deserializeFailure( + response, + stackTraceWithoutCredentials(stackTrace) + ) + } + } + return transporter.requester.send(payload).then((response) => { + return retryDecision(response, decisions) + }) + } + /** + * Finally, for each retryable host perform request until we got a non + * retryable response. Some notes here: + * + * 1. The reverse here is applied so we can apply a `pop` later on => more performant. + * 2. We also get from the retryable options a timeout multiplier that is tailored + * for the current context. + */ + return createRetryableOptions( + transporter.hostsCache, + statelessHosts + ).then((options) => { + return retry( + [...options.statelessHosts].reverse(), + options.getTimeout + ) + }) + } + + function createTransporter(options) { + const { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + hosts, + queryParameters, + headers + } = options + const transporter = { + hostsCache, + logger, + requester, + requestsCache, + responsesCache, + timeouts, + userAgent, + headers, + queryParameters, + hosts: hosts.map((host) => createStatelessHost(host)), + read(request, requestOptions) { + /** + * First, we compute the user request options. Now, keep in mind, + * that using request options the user is able to modified the intire + * payload of the request. Such as headers, query parameters, and others. + */ + const mappedRequestOptions = createMappedRequestOptions( + requestOptions, + transporter.timeouts.read + ) + const createRetryableRequest = () => { + /** + * Then, we prepare a function factory that contains the construction of + * the retryable request. At this point, we may *not* perform the actual + * request. But we want to have the function factory ready. + */ + return retryableRequest( + transporter, + transporter.hosts.filter( + (host) => (host.accept & CallEnum.Read) !== 0 + ), + request, + mappedRequestOptions + ) + } + /** + * Once we have the function factory ready, we need to determine of the + * request is "cacheable" - should be cached. Note that, once again, + * the user can force this option. + */ + const cacheable = + mappedRequestOptions.cacheable !== undefined + ? mappedRequestOptions.cacheable + : request.cacheable + /** + * If is not "cacheable", we immediatly trigger the retryable request, no + * need to check cache implementations. + */ + if (cacheable !== true) { + return createRetryableRequest() + } + /** + * If the request is "cacheable", we need to first compute the key to ask + * the cache implementations if this request is on progress or if the + * response already exists on the cache. + */ + const key = { + request, + mappedRequestOptions, + transporter: { + queryParameters: transporter.queryParameters, + headers: transporter.headers + } + } + /** + * With the computed key, we first ask the responses cache + * implemention if this request was been resolved before. + */ + return transporter.responsesCache.get( + key, + () => { + /** + * If the request has never resolved before, we actually ask if there + * is a current request with the same key on progress. + */ + return transporter.requestsCache.get(key, () => { + return ( + transporter.requestsCache + /** + * Finally, if there is no request in progress with the same key, + * this `createRetryableRequest()` will actually trigger the + * retryable request. + */ + .set(key, createRetryableRequest()) + .then( + (response) => + Promise.all([ + transporter.requestsCache.delete(key), + response + ]), + (err) => + Promise.all([ + transporter.requestsCache.delete(key), + Promise.reject(err) + ]) + ) + .then(([_, response]) => response) + ) + }) + }, + { + /** + * Of course, once we get this response back from the server, we + * tell response cache to actually store the received response + * to be used later. + */ + miss: (response) => + transporter.responsesCache.set(key, response) + } + ) + }, + write(request, requestOptions) { + /** + * On write requests, no cache mechanisms are applied, and we + * proxy the request immediately to the requester. + */ + return retryableRequest( + transporter, + transporter.hosts.filter( + (host) => (host.accept & CallEnum.Write) !== 0 + ), + request, + createMappedRequestOptions( + requestOptions, + transporter.timeouts.write + ) + ) + } + } + return transporter + } + + function createUserAgent(version) { + const userAgent = { + value: `Algolia for JavaScript (${version})`, + add(options) { + const addedUserAgent = `; ${options.segment}${ + options.version !== undefined ? ` (${options.version})` : '' + }` + if (userAgent.value.indexOf(addedUserAgent) === -1) { + // eslint-disable-next-line functional/immutable-data + userAgent.value = `${userAgent.value}${addedUserAgent}` + } + return userAgent + } + } + return userAgent + } + + function deserializeSuccess(response) { + // eslint-disable-next-line functional/no-try-statement + try { + return JSON.parse(response.content) + } catch (e) { + throw createDeserializationError(e.message, response) + } + } + function deserializeFailure({ content, status }, stackFrame) { + // eslint-disable-next-line functional/no-let + let message = content + // eslint-disable-next-line functional/no-try-statement + try { + message = JSON.parse(content).message + } catch (e) { + // .. + } + return createApiError(message, status, stackFrame) + } + + // eslint-disable-next-line functional/prefer-readonly-type + function encode(format, ...args) { + // eslint-disable-next-line functional/no-let + let i = 0 + return format.replace(/%s/g, () => encodeURIComponent(args[i++])) + } + + function serializeUrl(host, path, queryParameters) { + const queryParametersAsString = serializeQueryParameters( + queryParameters + ) + // eslint-disable-next-line functional/no-let + let url = `${host.protocol}://${host.url}/${ + path.charAt(0) === '/' ? path.substr(1) : path + }` + if (queryParametersAsString.length) { + url += `?${queryParametersAsString}` + } + return url + } + function serializeQueryParameters(parameters) { + const isObjectOrArray = (value) => + Object.prototype.toString.call(value) === '[object Object]' || + Object.prototype.toString.call(value) === '[object Array]' + return Object.keys(parameters) + .map((key) => + encode( + '%s=%s', + key, + isObjectOrArray(parameters[key]) + ? JSON.stringify(parameters[key]) + : parameters[key] + ) + ) + .join('&') + } + function serializeData(request, requestOptions) { + if ( + request.method === requesterCommon.MethodEnum.Get || + (request.data === undefined && requestOptions.data === undefined) + ) { + return undefined + } + const data = Array.isArray(request.data) + ? request.data + : { ...request.data, ...requestOptions.data } + return JSON.stringify(data) + } + function serializeHeaders(transporter, requestOptions) { + const headers = { + ...transporter.headers, + ...requestOptions.headers + } + const serializedHeaders = {} + Object.keys(headers).forEach((header) => { + const value = headers[header] + // @ts-ignore + // eslint-disable-next-line functional/immutable-data + serializedHeaders[header.toLowerCase()] = value + }) + return serializedHeaders + } + + function stackTraceWithoutCredentials(stackTrace) { + return stackTrace.map((stackFrame) => + stackFrameWithoutCredentials(stackFrame) + ) + } + function stackFrameWithoutCredentials(stackFrame) { + const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] + ? { 'x-algolia-api-key': '*****' } + : {} + return { + ...stackFrame, + request: { + ...stackFrame.request, + headers: { + ...stackFrame.request.headers, + ...modifiedHeaders + } + } + } + } + + function createApiError(message, status, transporterStackTrace) { + return { + name: 'ApiError', + message, + status, + transporterStackTrace + } + } + + function createDeserializationError(message, response) { + return { + name: 'DeserializationError', + message, + response + } + } + + function createRetryError(transporterStackTrace) { + return { + name: 'RetryError', + message: + 'Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.', + transporterStackTrace + } + } + + exports.CallEnum = CallEnum + exports.HostStatusEnum = HostStatusEnum + exports.createApiError = createApiError + exports.createDeserializationError = createDeserializationError + exports.createMappedRequestOptions = createMappedRequestOptions + exports.createRetryError = createRetryError + exports.createStatefulHost = createStatefulHost + exports.createStatelessHost = createStatelessHost + exports.createTransporter = createTransporter + exports.createUserAgent = createUserAgent + exports.deserializeFailure = deserializeFailure + exports.deserializeSuccess = deserializeSuccess + exports.isStatefulHostTimeouted = isStatefulHostTimeouted + exports.isStatefulHostUp = isStatefulHostUp + exports.serializeData = serializeData + exports.serializeHeaders = serializeHeaders + exports.serializeQueryParameters = serializeQueryParameters + exports.serializeUrl = serializeUrl + exports.stackFrameWithoutCredentials = stackFrameWithoutCredentials + exports.stackTraceWithoutCredentials = stackTraceWithoutCredentials + + /***/ + }, + + /***/ 2424: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + // eslint-disable-next-line functional/immutable-data, import/no-commonjs + module.exports = __webpack_require__(3056) + + /***/ + }, + + /***/ 447: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + var cacheCommon = __webpack_require__(8848) + var cacheInMemory = __webpack_require__(8069) + var clientAnalytics = __webpack_require__(7538) + var clientCommon = __webpack_require__(1905) + var clientRecommendation = __webpack_require__(31) + var clientSearch = __webpack_require__(2425) + var loggerCommon = __webpack_require__(3564) + var requesterNodeHttp = __webpack_require__(2724) + var transporter = __webpack_require__(2424) + + function algoliasearch(appId, apiKey, options) { + const commonOptions = { + appId, + apiKey, + timeouts: { + connect: 2, + read: 5, + write: 30 + }, + requester: requesterNodeHttp.createNodeHttpRequester(), + logger: loggerCommon.createNullLogger(), + responsesCache: cacheCommon.createNullCache(), + requestsCache: cacheCommon.createNullCache(), + hostsCache: cacheInMemory.createInMemoryCache(), + userAgent: transporter.createUserAgent(clientCommon.version).add({ + segment: 'Node.js', + version: process.versions.node + }) + } + return clientSearch.createSearchClient({ + ...commonOptions, + ...options, + methods: { + search: clientSearch.multipleQueries, + searchForFacetValues: clientSearch.multipleSearchForFacetValues, + multipleBatch: clientSearch.multipleBatch, + multipleGetObjects: clientSearch.multipleGetObjects, + multipleQueries: clientSearch.multipleQueries, + copyIndex: clientSearch.copyIndex, + copySettings: clientSearch.copySettings, + copyRules: clientSearch.copyRules, + copySynonyms: clientSearch.copySynonyms, + moveIndex: clientSearch.moveIndex, + listIndices: clientSearch.listIndices, + getLogs: clientSearch.getLogs, + listClusters: clientSearch.listClusters, + multipleSearchForFacetValues: + clientSearch.multipleSearchForFacetValues, + getApiKey: clientSearch.getApiKey, + addApiKey: clientSearch.addApiKey, + listApiKeys: clientSearch.listApiKeys, + updateApiKey: clientSearch.updateApiKey, + deleteApiKey: clientSearch.deleteApiKey, + restoreApiKey: clientSearch.restoreApiKey, + assignUserID: clientSearch.assignUserID, + assignUserIDs: clientSearch.assignUserIDs, + getUserID: clientSearch.getUserID, + searchUserIDs: clientSearch.searchUserIDs, + listUserIDs: clientSearch.listUserIDs, + getTopUserIDs: clientSearch.getTopUserIDs, + removeUserID: clientSearch.removeUserID, + hasPendingMappings: clientSearch.hasPendingMappings, + generateSecuredApiKey: clientSearch.generateSecuredApiKey, + getSecuredApiKeyRemainingValidity: + clientSearch.getSecuredApiKeyRemainingValidity, + destroy: clientCommon.destroy, + initIndex: (base) => (indexName) => { + return clientSearch.initIndex(base)(indexName, { + methods: { + batch: clientSearch.batch, + delete: clientSearch.deleteIndex, + findAnswers: clientSearch.findAnswers, + getObject: clientSearch.getObject, + getObjects: clientSearch.getObjects, + saveObject: clientSearch.saveObject, + saveObjects: clientSearch.saveObjects, + search: clientSearch.search, + searchForFacetValues: clientSearch.searchForFacetValues, + waitTask: clientSearch.waitTask, + setSettings: clientSearch.setSettings, + getSettings: clientSearch.getSettings, + partialUpdateObject: clientSearch.partialUpdateObject, + partialUpdateObjects: clientSearch.partialUpdateObjects, + deleteObject: clientSearch.deleteObject, + deleteObjects: clientSearch.deleteObjects, + deleteBy: clientSearch.deleteBy, + clearObjects: clientSearch.clearObjects, + browseObjects: clientSearch.browseObjects, + getObjectPosition: clientSearch.getObjectPosition, + findObject: clientSearch.findObject, + exists: clientSearch.exists, + saveSynonym: clientSearch.saveSynonym, + saveSynonyms: clientSearch.saveSynonyms, + getSynonym: clientSearch.getSynonym, + searchSynonyms: clientSearch.searchSynonyms, + browseSynonyms: clientSearch.browseSynonyms, + deleteSynonym: clientSearch.deleteSynonym, + clearSynonyms: clientSearch.clearSynonyms, + replaceAllObjects: clientSearch.replaceAllObjects, + replaceAllSynonyms: clientSearch.replaceAllSynonyms, + searchRules: clientSearch.searchRules, + getRule: clientSearch.getRule, + deleteRule: clientSearch.deleteRule, + saveRule: clientSearch.saveRule, + saveRules: clientSearch.saveRules, + replaceAllRules: clientSearch.replaceAllRules, + browseRules: clientSearch.browseRules, + clearRules: clientSearch.clearRules + } + }) + }, + initAnalytics: () => (clientOptions) => { + return clientAnalytics.createAnalyticsClient({ + ...commonOptions, + ...clientOptions, + methods: { + addABTest: clientAnalytics.addABTest, + getABTest: clientAnalytics.getABTest, + getABTests: clientAnalytics.getABTests, + stopABTest: clientAnalytics.stopABTest, + deleteABTest: clientAnalytics.deleteABTest + } + }) + }, + initRecommendation: () => (clientOptions) => { + return clientRecommendation.createRecommendationClient({ + ...commonOptions, + ...clientOptions, + methods: { + getPersonalizationStrategy: + clientRecommendation.getPersonalizationStrategy, + setPersonalizationStrategy: + clientRecommendation.setPersonalizationStrategy + } + }) + } + } + }) + } + // eslint-disable-next-line functional/immutable-data + algoliasearch.version = clientCommon.version + + module.exports = algoliasearch + + /***/ + }, + + /***/ 930: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + /* eslint-disable functional/immutable-data, import/no-commonjs */ + const algoliasearch = __webpack_require__(447) + + /** + * The Common JS build is the default entry point for the Node environment. Keep in + * in mind, that for the browser environment, we hint the bundler to use the UMD + * build instead as specified on the key `browser` of our `package.json` file. + */ + module.exports = algoliasearch + + /** + * In addition, we also set explicitly the default export below making + * this Common JS module in compliance with es6 modules specification. + */ + module.exports.default = algoliasearch + + /***/ + }, + + /***/ 7240: /***/ (module) => { + 'use strict' + + module.exports = bail + + function bail(err) { + if (err) { + throw err + } + } + + /***/ + }, + + /***/ 421: /***/ (module) => { + var charenc = { + // UTF-8 encoding + utf8: { + // Convert a string to a byte array + stringToBytes: function (str) { + return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))) + }, + + // Convert a byte array to a string + bytesToString: function (bytes) { + return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))) + } + }, + + // Binary encoding + bin: { + // Convert a string to a byte array + stringToBytes: function (str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xff) + return bytes + }, + + // Convert a byte array to a string + bytesToString: function (bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])) + return str.join('') + } + } + } + + module.exports = charenc + + /***/ + }, + + /***/ 2194: /***/ (__unused_webpack_module, exports) => { + 'use strict' + + exports.parse = parse + exports.stringify = stringify + + var comma = ',' + var space = ' ' + var empty = '' + + // Parse comma-separated tokens to an array. + function parse(value) { + var values = [] + var input = String(value || empty) + var index = input.indexOf(comma) + var lastIndex = 0 + var end = false + var val + + while (!end) { + if (index === -1) { + index = input.length + end = true + } + + val = input.slice(lastIndex, index).trim() + + if (val || !end) { + values.push(val) + } + + lastIndex = index + 1 + index = input.indexOf(comma, lastIndex) + } + + return values + } + + // Compile an array to comma-separated tokens. + // `options.padLeft` (default: `true`) pads a space left of each token, and + // `options.padRight` (default: `false`) pads a space to the right of each token. + function stringify(values, options) { + var settings = options || {} + var left = settings.padLeft === false ? empty : space + var right = settings.padRight ? space : empty + + // Ensure the last empty entry is seen. + if (values[values.length - 1] === empty) { + values = values.concat(empty) + } + + return values.join(right + comma + left).trim() + } + + /***/ + }, + + /***/ 7935: /***/ (module) => { + ;(function () { + var base64map = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', + crypt = { + // Bit-wise rotation left + rotl: function (n, b) { + return (n << b) | (n >>> (32 - b)) + }, + + // Bit-wise rotation right + rotr: function (n, b) { + return (n << (32 - b)) | (n >>> b) + }, + + // Swap big-endian to little-endian and vice versa + endian: function (n) { + // If number given, swap endian + if (n.constructor == Number) { + return ( + (crypt.rotl(n, 8) & 0x00ff00ff) | + (crypt.rotl(n, 24) & 0xff00ff00) + ) + } + + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) n[i] = crypt.endian(n[i]) + return n + }, + + // Generate an array of any length of random bytes + randomBytes: function (n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)) + return bytes + }, + + // Convert a byte array to big-endian 32-bit words + bytesToWords: function (bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= bytes[i] << (24 - (b % 32)) + return words + }, + + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function (words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - (b % 32))) & 0xff) + return bytes + }, + + // Convert a byte array to a hex string + bytesToHex: function (bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)) + hex.push((bytes[i] & 0xf).toString(16)) + } + return hex.join('') + }, + + // Convert a hex string to a byte array + hexToBytes: function (hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)) + return bytes + }, + + // Convert a byte array to a base-64 string + bytesToBase64: function (bytes) { + for (var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = + (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2] + for (var j = 0; j < 4; j++) + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push( + base64map.charAt((triplet >>> (6 * (3 - j))) & 0x3f) + ) + else base64.push('=') + } + return base64.join('') + }, + + // Convert a base-64 string to a byte array + base64ToBytes: function (base64) { + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/gi, '') + + for ( + var bytes = [], i = 0, imod4 = 0; + i < base64.length; + imod4 = ++i % 4 + ) { + if (imod4 == 0) continue + bytes.push( + ((base64map.indexOf(base64.charAt(i - 1)) & + (Math.pow(2, -2 * imod4 + 8) - 1)) << + (imod4 * 2)) | + (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)) + ) + } + return bytes + } + } + + module.exports = crypt + })() + + /***/ + }, + + /***/ 8171: /***/ (module) => { + 'use strict' + + var hasOwn = Object.prototype.hasOwnProperty + var toStr = Object.prototype.toString + var defineProperty = Object.defineProperty + var gOPD = Object.getOwnPropertyDescriptor + + var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr) + } -var search = /[#.]/g + return toStr.call(arr) === '[object Array]' + } + + var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false + } -// Create a hast element from a simple CSS selector. -function parse(selector, defaultTagName) { - var value = selector || '' - var name = defaultTagName || 'div' - var props = {} - var start = 0 - var subvalue - var previous - var match + var hasOwnConstructor = hasOwn.call(obj, 'constructor') + var hasIsPrototypeOf = + obj.constructor && + obj.constructor.prototype && + hasOwn.call(obj.constructor.prototype, 'isPrototypeOf') + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false + } - while (start < value.length) { - search.lastIndex = start - match = search.exec(value) - subvalue = value.slice(start, match ? match.index : value.length) + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key + for (key in obj) { + /**/ + } - if (subvalue) { - if (!previous) { - name = subvalue - } else if (previous === '#') { - props.id = subvalue - } else if (props.className) { - props.className.push(subvalue) - } else { - props.className = [subvalue] + return typeof key === 'undefined' || hasOwn.call(obj, key) } - start += subvalue.length - } + // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target + var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }) + } else { + target[options.name] = options.newValue + } + } - if (match) { - previous = match[0] - start++ - } - } - - return {type: 'element', tagName: name, properties: props, children: []} -} - - -/***/ }), - -/***/ 3233: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var Parser = __webpack_require__(2884) -var pos = __webpack_require__(1133) -var fromParse5 = __webpack_require__(8849) -var toParse5 = __webpack_require__(2785) -var voids = __webpack_require__(4318) -var ns = __webpack_require__(4992) -var zwitch = __webpack_require__(1067) -var xtend = __webpack_require__(1208) - -module.exports = wrap - -var inTemplateMode = 'IN_TEMPLATE_MODE' -var dataState = 'DATA_STATE' -var characterToken = 'CHARACTER_TOKEN' -var startTagToken = 'START_TAG_TOKEN' -var endTagToken = 'END_TAG_TOKEN' -var commentToken = 'COMMENT_TOKEN' -var doctypeToken = 'DOCTYPE_TOKEN' - -var parseOptions = { - sourceCodeLocationInfo: true, - scriptingEnabled: false -} - -function wrap(tree, file) { - var parser = new Parser(parseOptions) - var one = zwitch('type') - var tokenizer - var preprocessor - var posTracker - var locationTracker - var result - - one.handlers.root = root - one.handlers.element = element - one.handlers.text = text - one.handlers.comment = comment - one.handlers.doctype = doctype - one.handlers.raw = raw - one.unknown = unknown - - result = fromParse5(documentMode(tree) ? document() : fragment(), file) - - // Unpack if possible and when not given a `root`. - if (tree.type !== 'root' && result.children.length === 1) { - return result.children[0] - } - - return result - - function fragment() { - var context - var mock - var doc - - context = { - nodeName: 'template', - tagName: 'template', - attrs: [], - namespaceURI: ns.html, - childNodes: [] - } + // Return undefined instead of __proto__ if '__proto__' is not an own property + var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0 + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value + } + } - mock = { - nodeName: 'documentmock', - tagName: 'documentmock', - attrs: [], - namespaceURI: ns.html, - childNodes: [] - } + return obj[name] + } - doc = { - nodeName: '#document-fragment', - childNodes: [] - } + module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone + var target = arguments[0] + var i = 1 + var length = arguments.length + var deep = false - parser._bootstrap(mock, context) - parser._pushTmplInsertionMode(inTemplateMode) - parser._initTokenizerForFragmentParsing() - parser._insertFakeRootElement() - parser._resetInsertionMode() - parser._findFormInFragmentContext() + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target + target = arguments[1] || {} + // skip the boolean and the target + i = 2 + } + if ( + target == null || + (typeof target !== 'object' && typeof target !== 'function') + ) { + target = {} + } + + for (; i < length; ++i) { + options = arguments[i] + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name) + copy = getProperty(options, name) + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if ( + deep && + copy && + (isPlainObject(copy) || (copyIsArray = isArray(copy))) + ) { + if (copyIsArray) { + copyIsArray = false + clone = src && isArray(src) ? src : [] + } else { + clone = src && isPlainObject(src) ? src : {} + } + + // Never move original objects, clone them + setProperty(target, { + name: name, + newValue: extend(deep, clone, copy) + }) + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }) + } + } + } + } + } - tokenizer = parser.tokenizer - preprocessor = tokenizer.preprocessor - locationTracker = tokenizer.__mixins[0] - posTracker = locationTracker.posTracker + // Return the modified object + return target + } - one(tree) + /***/ + }, - parser._adoptNodes(mock.childNodes[0], doc) + /***/ 237: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + var emoji = __webpack_require__(5464) - return doc - } + module.exports = BananaSlug - function document() { - var doc = parser.treeAdapter.createDocument() + var own = Object.hasOwnProperty + var whitespace = /\s/g + var specials = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~’]/g - parser._bootstrap(doc, null) - tokenizer = parser.tokenizer - preprocessor = tokenizer.preprocessor - locationTracker = tokenizer.__mixins[0] - posTracker = locationTracker.posTracker + function BananaSlug() { + var self = this - one(tree) + if (!(self instanceof BananaSlug)) return new BananaSlug() - return doc - } + self.reset() + } - function all(nodes) { - var length = 0 - var index = -1 + /** + * Generate a unique slug. + * @param {string} value String of text to slugify + * @param {boolean} [false] Keep the current case, otherwise make all lowercase + * @return {string} A unique slug string + */ + BananaSlug.prototype.slug = function (value, maintainCase) { + var self = this + var slug = slugger(value, maintainCase === true) + var originalSlug = slug - /* istanbul ignore else - invalid nodes, see rehypejs/rehype-raw#7. */ - if (nodes) { - length = nodes.length - } + while (own.call(self.occurrences, slug)) { + self.occurrences[originalSlug]++ + slug = originalSlug + '-' + self.occurrences[originalSlug] + } - while (++index < length) { - one(nodes[index]) - } - } + self.occurrences[slug] = 0 + + return slug + } + + /** + * Reset - Forget all previous slugs + * @return void + */ + BananaSlug.prototype.reset = function () { + this.occurrences = Object.create(null) + } + + function slugger(string, maintainCase) { + if (typeof string !== 'string') return '' + if (!maintainCase) string = string.toLowerCase() + + return string + .trim() + .replace(specials, '') + .replace(emoji(), '') + .replace(whitespace, '-') + } + + BananaSlug.slug = slugger + + /***/ + }, + + /***/ 5464: /***/ (module) => { + module.exports = function () { + return /[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267B\u267F\u2692-\u2694\u2696\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD79\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED0\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3]|\uD83E[\uDD10-\uDD18\uDD80-\uDD84\uDDC0]|\uD83C\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uD83C\uDDFE\uD83C[\uDDEA\uDDF9]|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDFC\uD83C[\uDDEB\uDDF8]|\uD83C\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uD83C\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF8\uDDFE\uDDFF]|\uD83C\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uD83C\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uD83C\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uD83C\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uD83C\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uD83C\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uD83C\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uD83C\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uD83C\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uD83C\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uD83C\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uD83C\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uD83C\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uD83C\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uD83C\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uD83C\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|[#\*0-9]\u20E3/g + } + + /***/ + }, + + /***/ 4547: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + var html = __webpack_require__(9515) + var svg = __webpack_require__(4589) + var find = __webpack_require__(3657) + var hastToReact = __webpack_require__(3934) + var spaces = __webpack_require__(4158) + var commas = __webpack_require__(2194) + var style = __webpack_require__(6204) + var ns = __webpack_require__(4992) + var convert = __webpack_require__(4070) + + var root = convert('root') + var element = convert('element') + var text = convert('text') + + module.exports = wrapper + + function wrapper(h, node, options) { + var settings = options || {} + var r = react(h) + var v = vue(h) + var vd = vdom(h) + var prefix + + if (typeof h !== 'function') { + throw new Error('h is not a function') + } + + if (typeof settings === 'string' || typeof settings === 'boolean') { + prefix = settings + settings = {} + } else { + prefix = settings.prefix + } + + if (root(node)) { + node = + node.children.length === 1 && element(node.children[0]) + ? node.children[0] + : { + type: 'element', + tagName: 'div', + properties: {}, + children: node.children + } + } else if (!element(node)) { + throw new Error( + 'Expected root or element, not `' + + ((node && node.type) || node) + + '`' + ) + } + + return toH(h, node, { + schema: settings.space === 'svg' ? svg : html, + prefix: prefix == null ? (r || v || vd ? 'h-' : null) : prefix, + key: 0, + react: r, + vue: v, + vdom: vd, + hyperscript: hyperscript(h) + }) + } + + // Transform a hast node through a hyperscript interface to *anything*! + function toH(h, node, ctx) { + var parentSchema = ctx.schema + var schema = parentSchema + var name = node.tagName + var attributes = {} + var nodes = [] + var index = -1 + var key + var value + + if (parentSchema.space === 'html' && name.toLowerCase() === 'svg') { + schema = svg + ctx.schema = schema + } + + for (key in node.properties) { + addAttribute(attributes, key, node.properties[key], ctx, name) + } + + if (ctx.vdom) { + if (schema.space === 'html') { + name = name.toUpperCase() + } else { + attributes.namespace = ns[schema.space] + } + } + + if (ctx.prefix) { + ctx.key++ + attributes.key = ctx.prefix + ctx.key + } + + if (node.children) { + while (++index < node.children.length) { + value = node.children[index] + + if (element(value)) { + nodes.push(toH(h, value, ctx)) + } else if (text(value)) { + nodes.push(value.value) + } + } + } + + // Restore parent schema. + ctx.schema = parentSchema + + // Ensure no React warnings are triggered for void elements having children + // passed in. + return nodes.length + ? h.call(node, name, attributes, nodes) + : h.call(node, name, attributes) + } + + function addAttribute(props, prop, value, ctx, name) { + var info = find(ctx.schema, prop) + var subprop + + // Ignore nullish and `NaN` values. + // Ignore `false` and falsey known booleans for hyperlike DSLs. + if ( + value == null || + value !== value || + (value === false && (ctx.vue || ctx.vdom || ctx.hyperscript)) || + (!value && info.boolean && (ctx.vue || ctx.vdom || ctx.hyperscript)) + ) { + return + } + + if (value && typeof value === 'object' && 'length' in value) { + // Accept `array`. + // Most props are space-separated. + value = (info.commaSeparated ? commas : spaces).stringify(value) + } + + // Treat `true` and truthy known booleans. + if (info.boolean && ctx.hyperscript) { + value = '' + } + + // VDOM, Vue, and React accept `style` as object. + if ( + info.property === 'style' && + typeof value === 'string' && + (ctx.react || ctx.vue || ctx.vdom) + ) { + value = parseStyle(value, name) + } + + if (ctx.vue) { + if (info.property !== 'style') subprop = 'attrs' + } else if (!info.mustUseProperty) { + if (ctx.vdom) { + if (info.property !== 'style') subprop = 'attributes' + } else if (ctx.hyperscript) { + subprop = 'attrs' + } + } + + if (subprop) { + if (!props[subprop]) props[subprop] = {} + props[subprop][info.attribute] = value + } else if (info.space && ctx.react) { + props[hastToReact[info.property] || info.property] = value + } else { + props[info.attribute] = value + } + } + + // Check if `h` is `react.createElement`. + function react(h) { + var node = h && h('div') + return Boolean( + node && ('_owner' in node || '_store' in node) && node.key == null + ) + } + + // Check if `h` is `hyperscript`. + function hyperscript(h) { + return Boolean(h && h.context && h.cleanup) + } + + // Check if `h` is `virtual-dom/h`. + function vdom(h) { + return h && h('div').type === 'VirtualNode' + } + + function vue(h) { + var node = h && h('div') + return Boolean(node && node.context && node.context._isVue) + } + + function parseStyle(value, tagName) { + var result = {} + + try { + style(value, iterator) + } catch (error) { + error.message = + tagName + '[style]' + error.message.slice('undefined'.length) + throw error + } + + return result + + function iterator(name, value) { + if (name.slice(0, 4) === '-ms-') name = 'ms-' + name.slice(4) + result[name.replace(/-([a-z])/g, styleReplacer)] = value + } + } + + function styleReplacer($0, $1) { + return $1.toUpperCase() + } + + /***/ + }, + + /***/ 8849: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + var s = __webpack_require__(3413) + var h = __webpack_require__(7156) + var find = __webpack_require__(3657) + var html = __webpack_require__(9515) + var svg = __webpack_require__(4589) + var vfileLocation = __webpack_require__(2403) + var ns = __webpack_require__(4992) + + module.exports = wrapper + + var own = {}.hasOwnProperty + + // Handlers. + var map = { + '#document': root, + '#document-fragment': root, + '#text': text, + '#comment': comment, + '#documentType': doctype + } + + // Wrapper to normalise options. + function wrapper(ast, options) { + var settings = options || {} + var file + + if (settings.messages) { + file = settings + settings = {} + } else { + file = settings.file + } + + return transform(ast, { + schema: settings.space === 'svg' ? svg : html, + file: file, + verbose: settings.verbose + }) + } + + // Transform a node. + function transform(ast, config) { + var schema = config.schema + var fn = own.call(map, ast.nodeName) ? map[ast.nodeName] : element + var children + var result + var position + + if (fn === element) { + config.schema = ast.namespaceURI === ns.svg ? svg : html + } + + if (ast.childNodes) { + children = nodes(ast.childNodes, config) + } + + result = fn(ast, children, config) + + if (ast.sourceCodeLocation && config.file) { + position = location(result, ast.sourceCodeLocation, config) + + if (position) { + config.location = true + result.position = position + } + } + + config.schema = schema + + return result + } + + // Transform children. + function nodes(children, config) { + var index = -1 + var result = [] + + while (++index < children.length) { + result[index] = transform(children[index], config) + } + + return result + } + + // Transform a document. + // Stores `ast.quirksMode` in `node.data.quirksMode`. + function root(ast, children, config) { + var result = { + type: 'root', + children: children, + data: { + quirksMode: ast.mode === 'quirks' || ast.mode === 'limited-quirks' + } + } + var doc + var location + + if (config.file && config.location) { + doc = String(config.file) + location = vfileLocation(doc) + result.position = { + start: location.toPoint(0), + end: location.toPoint(doc.length) + } + } + + return result + } + + // Transform a doctype. + function doctype(ast) { + return { + type: 'doctype', + name: ast.name || '', + public: ast.publicId || null, + system: ast.systemId || null + } + } + + // Transform a text. + function text(ast) { + return { type: 'text', value: ast.value } + } + + // Transform a comment. + function comment(ast) { + return { type: 'comment', value: ast.data } + } + + // Transform an element. + function element(ast, children, config) { + var fn = config.schema.space === 'svg' ? s : h + var props = {} + var index = -1 + var result + var attribute + var pos + var start + var end + + while (++index < ast.attrs.length) { + attribute = ast.attrs[index] + props[ + (attribute.prefix ? attribute.prefix + ':' : '') + attribute.name + ] = attribute.value + } + + result = fn(ast.tagName, props, children) + + if (result.tagName === 'template' && 'content' in ast) { + pos = ast.sourceCodeLocation + start = pos && pos.startTag && position(pos.startTag).end + end = pos && pos.endTag && position(pos.endTag).start + + result.content = transform(ast.content, config) + + if ((start || end) && config.file) { + result.content.position = { start: start, end: end } + } + } + + return result + } + + // Create clean positional information. + function location(node, location, config) { + var result = position(location) + var tail + var key + var props + + if (node.type === 'element') { + tail = node.children[node.children.length - 1] + + // Bug for unclosed with children. + // See: . + if (!location.endTag && tail && tail.position && tail.position.end) { + result.end = Object.assign({}, tail.position.end) + } + + if (config.verbose) { + props = {} + + for (key in location.attrs) { + props[find(config.schema, key).property] = position( + location.attrs[key] + ) + } + + node.data = { + position: { + opening: position(location.startTag), + closing: location.endTag ? position(location.endTag) : null, + properties: props + } + } + } + } + + return result + } + + function position(loc) { + var start = point({ + line: loc.startLine, + column: loc.startCol, + offset: loc.startOffset + }) + var end = point({ + line: loc.endLine, + column: loc.endCol, + offset: loc.endOffset + }) + return start || end ? { start: start, end: end } : null + } + + function point(point) { + return point.line && point.column ? point : null + } + + /***/ + }, + + /***/ 5253: /***/ (module) => { + 'use strict' + + module.exports = parse + + var search = /[#.]/g + + // Create a hast element from a simple CSS selector. + function parse(selector, defaultTagName) { + var value = selector || '' + var name = defaultTagName || 'div' + var props = {} + var start = 0 + var subvalue + var previous + var match + + while (start < value.length) { + search.lastIndex = start + match = search.exec(value) + subvalue = value.slice(start, match ? match.index : value.length) + + if (subvalue) { + if (!previous) { + name = subvalue + } else if (previous === '#') { + props.id = subvalue + } else if (props.className) { + props.className.push(subvalue) + } else { + props.className = [subvalue] + } + + start += subvalue.length + } + + if (match) { + previous = match[0] + start++ + } + } + + return { + type: 'element', + tagName: name, + properties: props, + children: [] + } + } + + /***/ + }, + + /***/ 3233: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + var Parser = __webpack_require__(2884) + var pos = __webpack_require__(1133) + var fromParse5 = __webpack_require__(8849) + var toParse5 = __webpack_require__(2785) + var voids = __webpack_require__(4318) + var ns = __webpack_require__(4992) + var zwitch = __webpack_require__(1067) + var xtend = __webpack_require__(1208) + + module.exports = wrap + + var inTemplateMode = 'IN_TEMPLATE_MODE' + var dataState = 'DATA_STATE' + var characterToken = 'CHARACTER_TOKEN' + var startTagToken = 'START_TAG_TOKEN' + var endTagToken = 'END_TAG_TOKEN' + var commentToken = 'COMMENT_TOKEN' + var doctypeToken = 'DOCTYPE_TOKEN' + + var parseOptions = { + sourceCodeLocationInfo: true, + scriptingEnabled: false + } + + function wrap(tree, file) { + var parser = new Parser(parseOptions) + var one = zwitch('type') + var tokenizer + var preprocessor + var posTracker + var locationTracker + var result + + one.handlers.root = root + one.handlers.element = element + one.handlers.text = text + one.handlers.comment = comment + one.handlers.doctype = doctype + one.handlers.raw = raw + one.unknown = unknown + + result = fromParse5(documentMode(tree) ? document() : fragment(), file) + + // Unpack if possible and when not given a `root`. + if (tree.type !== 'root' && result.children.length === 1) { + return result.children[0] + } + + return result + + function fragment() { + var context + var mock + var doc + + context = { + nodeName: 'template', + tagName: 'template', + attrs: [], + namespaceURI: ns.html, + childNodes: [] + } + + mock = { + nodeName: 'documentmock', + tagName: 'documentmock', + attrs: [], + namespaceURI: ns.html, + childNodes: [] + } + + doc = { + nodeName: '#document-fragment', + childNodes: [] + } + + parser._bootstrap(mock, context) + parser._pushTmplInsertionMode(inTemplateMode) + parser._initTokenizerForFragmentParsing() + parser._insertFakeRootElement() + parser._resetInsertionMode() + parser._findFormInFragmentContext() + + tokenizer = parser.tokenizer + preprocessor = tokenizer.preprocessor + locationTracker = tokenizer.__mixins[0] + posTracker = locationTracker.posTracker + + one(tree) + + parser._adoptNodes(mock.childNodes[0], doc) + + return doc + } + + function document() { + var doc = parser.treeAdapter.createDocument() + + parser._bootstrap(doc, null) + tokenizer = parser.tokenizer + preprocessor = tokenizer.preprocessor + locationTracker = tokenizer.__mixins[0] + posTracker = locationTracker.posTracker + + one(tree) + + return doc + } + + function all(nodes) { + var length = 0 + var index = -1 + + /* istanbul ignore else - invalid nodes, see rehypejs/rehype-raw#7. */ + if (nodes) { + length = nodes.length + } + + while (++index < length) { + one(nodes[index]) + } + } - function root(node) { - all(node.children) - } + function root(node) { + all(node.children) + } + + function element(node) { + var empty = voids.indexOf(node.tagName) !== -1 + + resetTokenizer() + parser._processToken(startTag(node), ns.html) + + all(node.children) + + if (!empty) { + resetTokenizer() + parser._processToken(endTag(node)) + } + } + + function text(node) { + resetTokenizer() + parser._processToken({ + type: characterToken, + chars: node.value, + location: createParse5Location(node) + }) + } + + function doctype(node) { + var p5 = toParse5(node) + resetTokenizer() + parser._processToken({ + type: doctypeToken, + name: p5.name, + forceQuirks: false, + publicId: p5.publicId, + systemId: p5.systemId, + location: createParse5Location(node) + }) + } + + function comment(node) { + resetTokenizer() + parser._processToken({ + type: commentToken, + data: node.value, + location: createParse5Location(node) + }) + } + + function raw(node) { + var start = pos.start(node) + var line = start.line || 1 + var column = start.column || 1 + var offset = start.offset || 0 + var token + + // Reset preprocessor: + // See: . + preprocessor.html = null + preprocessor.pos = -1 + preprocessor.lastGapPos = -1 + preprocessor.lastCharPos = -1 + preprocessor.gapStack = [] + preprocessor.skipNextNewLine = false + preprocessor.lastChunkWritten = false + preprocessor.endOfChunkHit = false + + // Reset preprocessor mixin: + // See: . + posTracker.isEol = false + posTracker.lineStartPos = -column + 1 // Looks weird, but ensures we get correct positional info. + posTracker.droppedBufferSize = offset + posTracker.offset = 0 + posTracker.col = 1 + posTracker.line = line + + // Reset location tracker: + // See: . + locationTracker.currentAttrLocation = null + locationTracker.ctLoc = createParse5Location(node) + + // See the code for `parse` and `parseFragment`: + // See: . + tokenizer.write(node.value) + parser._runParsingLoop(null) + + // Process final characters if they’re still there after hibernating. + // Similar to: + // See: . + token = tokenizer.currentCharacterToken + + if (token) { + token.location.endLine = posTracker.line + token.location.endCol = posTracker.col + 1 + token.location.endOffset = posTracker.offset + 1 + parser._processToken(token) + } + } + + function resetTokenizer() { + // Reset tokenizer: + // See: . + // Especially putting it back in the `data` state is useful: some elements, + // like textareas and iframes, change the state. + // See GH-7. + // But also if broken HTML is in `raw`, and then a correct element is given. + // See GH-11. + tokenizer.tokenQueue = [] + tokenizer.state = dataState + tokenizer.returnState = '' + tokenizer.charRefCode = -1 + tokenizer.tempBuff = [] + tokenizer.lastStartTagName = '' + tokenizer.consumedAfterSnapshot = -1 + tokenizer.active = false + tokenizer.currentCharacterToken = null + tokenizer.currentToken = null + tokenizer.currentAttr = null + } + } + + function startTag(node) { + var location = createParse5Location(node) + + location.startTag = xtend(location) + + return { + type: startTagToken, + tagName: node.tagName, + selfClosing: false, + attrs: attributes(node), + location: location + } + } + + function attributes(node) { + return toParse5({ + tagName: node.tagName, + type: 'element', + properties: node.properties + }).attrs + } + + function endTag(node) { + var location = createParse5Location(node) + + location.endTag = xtend(location) + + return { + type: endTagToken, + tagName: node.tagName, + attrs: [], + location: location + } + } + + function unknown(node) { + throw new Error('Cannot compile `' + node.type + '` node') + } - function element(node) { - var empty = voids.indexOf(node.tagName) !== -1 + function documentMode(node) { + var head = node.type === 'root' ? node.children[0] : node - resetTokenizer() - parser._processToken(startTag(node), ns.html) + return head && (head.type === 'doctype' || head.tagName === 'html') + } - all(node.children) + function createParse5Location(node) { + var start = pos.start(node) + var end = pos.end(node) - if (!empty) { - resetTokenizer() - parser._processToken(endTag(node)) - } - } - - function text(node) { - resetTokenizer() - parser._processToken({ - type: characterToken, - chars: node.value, - location: createParse5Location(node) - }) - } - - function doctype(node) { - var p5 = toParse5(node) - resetTokenizer() - parser._processToken({ - type: doctypeToken, - name: p5.name, - forceQuirks: false, - publicId: p5.publicId, - systemId: p5.systemId, - location: createParse5Location(node) - }) - } - - function comment(node) { - resetTokenizer() - parser._processToken({ - type: commentToken, - data: node.value, - location: createParse5Location(node) - }) - } - - function raw(node) { - var start = pos.start(node) - var line = start.line || 1 - var column = start.column || 1 - var offset = start.offset || 0 - var token - - // Reset preprocessor: - // See: . - preprocessor.html = null - preprocessor.pos = -1 - preprocessor.lastGapPos = -1 - preprocessor.lastCharPos = -1 - preprocessor.gapStack = [] - preprocessor.skipNextNewLine = false - preprocessor.lastChunkWritten = false - preprocessor.endOfChunkHit = false - - // Reset preprocessor mixin: - // See: . - posTracker.isEol = false - posTracker.lineStartPos = -column + 1 // Looks weird, but ensures we get correct positional info. - posTracker.droppedBufferSize = offset - posTracker.offset = 0 - posTracker.col = 1 - posTracker.line = line - - // Reset location tracker: - // See: . - locationTracker.currentAttrLocation = null - locationTracker.ctLoc = createParse5Location(node) - - // See the code for `parse` and `parseFragment`: - // See: . - tokenizer.write(node.value) - parser._runParsingLoop(null) - - // Process final characters if they’re still there after hibernating. - // Similar to: - // See: . - token = tokenizer.currentCharacterToken - - if (token) { - token.location.endLine = posTracker.line - token.location.endCol = posTracker.col + 1 - token.location.endOffset = posTracker.offset + 1 - parser._processToken(token) - } - } - - function resetTokenizer() { - // Reset tokenizer: - // See: . - // Especially putting it back in the `data` state is useful: some elements, - // like textareas and iframes, change the state. - // See GH-7. - // But also if broken HTML is in `raw`, and then a correct element is given. - // See GH-11. - tokenizer.tokenQueue = [] - tokenizer.state = dataState - tokenizer.returnState = '' - tokenizer.charRefCode = -1 - tokenizer.tempBuff = [] - tokenizer.lastStartTagName = '' - tokenizer.consumedAfterSnapshot = -1 - tokenizer.active = false - tokenizer.currentCharacterToken = null - tokenizer.currentToken = null - tokenizer.currentAttr = null - } -} - -function startTag(node) { - var location = createParse5Location(node) - - location.startTag = xtend(location) - - return { - type: startTagToken, - tagName: node.tagName, - selfClosing: false, - attrs: attributes(node), - location: location - } -} - -function attributes(node) { - return toParse5({ - tagName: node.tagName, - type: 'element', - properties: node.properties - }).attrs -} - -function endTag(node) { - var location = createParse5Location(node) - - location.endTag = xtend(location) - - return { - type: endTagToken, - tagName: node.tagName, - attrs: [], - location: location - } -} - -function unknown(node) { - throw new Error('Cannot compile `' + node.type + '` node') -} - -function documentMode(node) { - var head = node.type === 'root' ? node.children[0] : node - - return head && (head.type === 'doctype' || head.tagName === 'html') -} - -function createParse5Location(node) { - var start = pos.start(node) - var end = pos.end(node) - - return { - startLine: start.line, - startCol: start.column, - startOffset: start.offset, - endLine: end.line, - endCol: end.column, - endOffset: end.offset - } -} - - -/***/ }), - -/***/ 2169: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -const { DOCUMENT_MODE } = __webpack_require__(4734); - -//Const -const VALID_DOCTYPE_NAME = 'html'; -const VALID_SYSTEM_ID = 'about:legacy-compat'; -const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; - -const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ - '+//silmaril//dtd html pro v0r11 19970101//', - '-//as//dtd html 3.0 aswedit + extensions//', - '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', - '-//ietf//dtd html 2.0 level 1//', - '-//ietf//dtd html 2.0 level 2//', - '-//ietf//dtd html 2.0 strict level 1//', - '-//ietf//dtd html 2.0 strict level 2//', - '-//ietf//dtd html 2.0 strict//', - '-//ietf//dtd html 2.0//', - '-//ietf//dtd html 2.1e//', - '-//ietf//dtd html 3.0//', - '-//ietf//dtd html 3.2 final//', - '-//ietf//dtd html 3.2//', - '-//ietf//dtd html 3//', - '-//ietf//dtd html level 0//', - '-//ietf//dtd html level 1//', - '-//ietf//dtd html level 2//', - '-//ietf//dtd html level 3//', - '-//ietf//dtd html strict level 0//', - '-//ietf//dtd html strict level 1//', - '-//ietf//dtd html strict level 2//', - '-//ietf//dtd html strict level 3//', - '-//ietf//dtd html strict//', - '-//ietf//dtd html//', - '-//metrius//dtd metrius presentational//', - '-//microsoft//dtd internet explorer 2.0 html strict//', - '-//microsoft//dtd internet explorer 2.0 html//', - '-//microsoft//dtd internet explorer 2.0 tables//', - '-//microsoft//dtd internet explorer 3.0 html strict//', - '-//microsoft//dtd internet explorer 3.0 html//', - '-//microsoft//dtd internet explorer 3.0 tables//', - '-//netscape comm. corp.//dtd html//', - '-//netscape comm. corp.//dtd strict html//', - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - '-//sq//dtd html 2.0 hotmetal + extensions//', - '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', - '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', - '-//spyglass//dtd html 2.0 extended//', - '-//sun microsystems corp.//dtd hotjava html//', - '-//sun microsystems corp.//dtd hotjava strict html//', - '-//w3c//dtd html 3 1995-03-24//', - '-//w3c//dtd html 3.2 draft//', - '-//w3c//dtd html 3.2 final//', - '-//w3c//dtd html 3.2//', - '-//w3c//dtd html 3.2s draft//', - '-//w3c//dtd html 4.0 frameset//', - '-//w3c//dtd html 4.0 transitional//', - '-//w3c//dtd html experimental 19960712//', - '-//w3c//dtd html experimental 970421//', - '-//w3c//dtd w3 html//', - '-//w3o//dtd w3 html 3.0//', - '-//webtechs//dtd mozilla html 2.0//', - '-//webtechs//dtd mozilla html//' -]; - -const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([ - '-//w3c//dtd html 4.01 frameset//', - '-//w3c//dtd html 4.01 transitional//' -]); - -const QUIRKS_MODE_PUBLIC_IDS = ['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']; -const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; - -const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([ - '-//w3c//dtd html 4.01 frameset//', - '-//w3c//dtd html 4.01 transitional//' -]); - -//Utils -function enquoteDoctypeId(id) { - const quote = id.indexOf('"') !== -1 ? "'" : '"'; - - return quote + id + quote; -} - -function hasPrefix(publicId, prefixes) { - for (let i = 0; i < prefixes.length; i++) { - if (publicId.indexOf(prefixes[i]) === 0) { - return true; + return { + startLine: start.line, + startCol: start.column, + startOffset: start.offset, + endLine: end.line, + endCol: end.column, + endOffset: end.offset } - } + } - return false; -} - -//API -exports.isConforming = function(token) { - return ( - token.name === VALID_DOCTYPE_NAME && - token.publicId === null && - (token.systemId === null || token.systemId === VALID_SYSTEM_ID) - ); -}; - -exports.getDocumentMode = function(token) { - if (token.name !== VALID_DOCTYPE_NAME) { - return DOCUMENT_MODE.QUIRKS; - } + /***/ + }, - const systemId = token.systemId; + /***/ 2169: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + const { DOCUMENT_MODE } = __webpack_require__(4734) + + //Const + const VALID_DOCTYPE_NAME = 'html' + const VALID_SYSTEM_ID = 'about:legacy-compat' + const QUIRKS_MODE_SYSTEM_ID = + 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd' + + const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ + '+//silmaril//dtd html pro v0r11 19970101//', + '-//as//dtd html 3.0 aswedit + extensions//', + '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', + '-//ietf//dtd html 2.0 level 1//', + '-//ietf//dtd html 2.0 level 2//', + '-//ietf//dtd html 2.0 strict level 1//', + '-//ietf//dtd html 2.0 strict level 2//', + '-//ietf//dtd html 2.0 strict//', + '-//ietf//dtd html 2.0//', + '-//ietf//dtd html 2.1e//', + '-//ietf//dtd html 3.0//', + '-//ietf//dtd html 3.2 final//', + '-//ietf//dtd html 3.2//', + '-//ietf//dtd html 3//', + '-//ietf//dtd html level 0//', + '-//ietf//dtd html level 1//', + '-//ietf//dtd html level 2//', + '-//ietf//dtd html level 3//', + '-//ietf//dtd html strict level 0//', + '-//ietf//dtd html strict level 1//', + '-//ietf//dtd html strict level 2//', + '-//ietf//dtd html strict level 3//', + '-//ietf//dtd html strict//', + '-//ietf//dtd html//', + '-//metrius//dtd metrius presentational//', + '-//microsoft//dtd internet explorer 2.0 html strict//', + '-//microsoft//dtd internet explorer 2.0 html//', + '-//microsoft//dtd internet explorer 2.0 tables//', + '-//microsoft//dtd internet explorer 3.0 html strict//', + '-//microsoft//dtd internet explorer 3.0 html//', + '-//microsoft//dtd internet explorer 3.0 tables//', + '-//netscape comm. corp.//dtd html//', + '-//netscape comm. corp.//dtd strict html//', + "-//o'reilly and associates//dtd html 2.0//", + "-//o'reilly and associates//dtd html extended 1.0//", + "-//o'reilly and associates//dtd html extended relaxed 1.0//", + '-//sq//dtd html 2.0 hotmetal + extensions//', + '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', + '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', + '-//spyglass//dtd html 2.0 extended//', + '-//sun microsystems corp.//dtd hotjava html//', + '-//sun microsystems corp.//dtd hotjava strict html//', + '-//w3c//dtd html 3 1995-03-24//', + '-//w3c//dtd html 3.2 draft//', + '-//w3c//dtd html 3.2 final//', + '-//w3c//dtd html 3.2//', + '-//w3c//dtd html 3.2s draft//', + '-//w3c//dtd html 4.0 frameset//', + '-//w3c//dtd html 4.0 transitional//', + '-//w3c//dtd html experimental 19960712//', + '-//w3c//dtd html experimental 970421//', + '-//w3c//dtd w3 html//', + '-//w3o//dtd w3 html 3.0//', + '-//webtechs//dtd mozilla html 2.0//', + '-//webtechs//dtd mozilla html//' + ] + + const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat( + [ + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//' + ] + ) - if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { - return DOCUMENT_MODE.QUIRKS; - } + const QUIRKS_MODE_PUBLIC_IDS = [ + '-//w3o//dtd w3 html strict 3.0//en//', + '-/w3c/dtd html 4.0 transitional/en', + 'html' + ] + const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = [ + '-//w3c//dtd xhtml 1.0 frameset//', + '-//w3c//dtd xhtml 1.0 transitional//' + ] + + const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat( + [ + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//' + ] + ) - let publicId = token.publicId; + //Utils + function enquoteDoctypeId(id) { + const quote = id.indexOf('"') !== -1 ? "'" : '"' - if (publicId !== null) { - publicId = publicId.toLowerCase(); + return quote + id + quote + } - if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) { - return DOCUMENT_MODE.QUIRKS; + function hasPrefix(publicId, prefixes) { + for (let i = 0; i < prefixes.length; i++) { + if (publicId.indexOf(prefixes[i]) === 0) { + return true + } } - let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; + return false + } + + //API + exports.isConforming = function (token) { + return ( + token.name === VALID_DOCTYPE_NAME && + token.publicId === null && + (token.systemId === null || token.systemId === VALID_SYSTEM_ID) + ) + } - if (hasPrefix(publicId, prefixes)) { - return DOCUMENT_MODE.QUIRKS; + exports.getDocumentMode = function (token) { + if (token.name !== VALID_DOCTYPE_NAME) { + return DOCUMENT_MODE.QUIRKS } - prefixes = - systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; + const systemId = token.systemId - if (hasPrefix(publicId, prefixes)) { - return DOCUMENT_MODE.LIMITED_QUIRKS; + if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { + return DOCUMENT_MODE.QUIRKS } - } - return DOCUMENT_MODE.NO_QUIRKS; -}; + let publicId = token.publicId -exports.serializeContent = function(name, publicId, systemId) { - let str = '!DOCTYPE '; + if (publicId !== null) { + publicId = publicId.toLowerCase() - if (name) { - str += name; - } - - if (publicId) { - str += ' PUBLIC ' + enquoteDoctypeId(publicId); - } else if (systemId) { - str += ' SYSTEM'; - } + if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) { + return DOCUMENT_MODE.QUIRKS + } - if (systemId !== null) { - str += ' ' + enquoteDoctypeId(systemId); - } + let prefixes = + systemId === null + ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES + : QUIRKS_MODE_PUBLIC_ID_PREFIXES - return str; -}; - - -/***/ }), - -/***/ 4068: -/***/ ((module) => { - -"use strict"; - - -module.exports = { - controlCharacterInInputStream: 'control-character-in-input-stream', - noncharacterInInputStream: 'noncharacter-in-input-stream', - surrogateInInputStream: 'surrogate-in-input-stream', - nonVoidHtmlElementStartTagWithTrailingSolidus: 'non-void-html-element-start-tag-with-trailing-solidus', - endTagWithAttributes: 'end-tag-with-attributes', - endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus', - unexpectedSolidusInTag: 'unexpected-solidus-in-tag', - unexpectedNullCharacter: 'unexpected-null-character', - unexpectedQuestionMarkInsteadOfTagName: 'unexpected-question-mark-instead-of-tag-name', - invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name', - unexpectedEqualsSignBeforeAttributeName: 'unexpected-equals-sign-before-attribute-name', - missingEndTagName: 'missing-end-tag-name', - unexpectedCharacterInAttributeName: 'unexpected-character-in-attribute-name', - unknownNamedCharacterReference: 'unknown-named-character-reference', - missingSemicolonAfterCharacterReference: 'missing-semicolon-after-character-reference', - unexpectedCharacterAfterDoctypeSystemIdentifier: 'unexpected-character-after-doctype-system-identifier', - unexpectedCharacterInUnquotedAttributeValue: 'unexpected-character-in-unquoted-attribute-value', - eofBeforeTagName: 'eof-before-tag-name', - eofInTag: 'eof-in-tag', - missingAttributeValue: 'missing-attribute-value', - missingWhitespaceBetweenAttributes: 'missing-whitespace-between-attributes', - missingWhitespaceAfterDoctypePublicKeyword: 'missing-whitespace-after-doctype-public-keyword', - missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: - 'missing-whitespace-between-doctype-public-and-system-identifiers', - missingWhitespaceAfterDoctypeSystemKeyword: 'missing-whitespace-after-doctype-system-keyword', - missingQuoteBeforeDoctypePublicIdentifier: 'missing-quote-before-doctype-public-identifier', - missingQuoteBeforeDoctypeSystemIdentifier: 'missing-quote-before-doctype-system-identifier', - missingDoctypePublicIdentifier: 'missing-doctype-public-identifier', - missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier', - abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier', - abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier', - cdataInHtmlContent: 'cdata-in-html-content', - incorrectlyOpenedComment: 'incorrectly-opened-comment', - eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text', - eofInDoctype: 'eof-in-doctype', - nestedComment: 'nested-comment', - abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment', - eofInComment: 'eof-in-comment', - incorrectlyClosedComment: 'incorrectly-closed-comment', - eofInCdata: 'eof-in-cdata', - absenceOfDigitsInNumericCharacterReference: 'absence-of-digits-in-numeric-character-reference', - nullCharacterReference: 'null-character-reference', - surrogateCharacterReference: 'surrogate-character-reference', - characterReferenceOutsideUnicodeRange: 'character-reference-outside-unicode-range', - controlCharacterReference: 'control-character-reference', - noncharacterCharacterReference: 'noncharacter-character-reference', - missingWhitespaceBeforeDoctypeName: 'missing-whitespace-before-doctype-name', - missingDoctypeName: 'missing-doctype-name', - invalidCharacterSequenceAfterDoctypeName: 'invalid-character-sequence-after-doctype-name', - duplicateAttribute: 'duplicate-attribute', - nonConformingDoctype: 'non-conforming-doctype', - missingDoctype: 'missing-doctype', - misplacedDoctype: 'misplaced-doctype', - endTagWithoutMatchingOpenElement: 'end-tag-without-matching-open-element', - closingOfElementWithOpenChildElements: 'closing-of-element-with-open-child-elements', - disallowedContentInNoscriptInHead: 'disallowed-content-in-noscript-in-head', - openElementsLeftAfterEof: 'open-elements-left-after-eof', - abandonedHeadElementChild: 'abandoned-head-element-child', - misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element', - nestedNoscriptInHead: 'nested-noscript-in-head', - eofInElementThatCanContainOnlyText: 'eof-in-element-that-can-contain-only-text' -}; - - -/***/ }), - -/***/ 4183: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -const Tokenizer = __webpack_require__(6386); -const HTML = __webpack_require__(4734); - -//Aliases -const $ = HTML.TAG_NAMES; -const NS = HTML.NAMESPACES; -const ATTRS = HTML.ATTRS; - -//MIME types -const MIME_TYPES = { - TEXT_HTML: 'text/html', - APPLICATION_XML: 'application/xhtml+xml' -}; - -//Attributes -const DEFINITION_URL_ATTR = 'definitionurl'; -const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; -const SVG_ATTRS_ADJUSTMENT_MAP = { - attributename: 'attributeName', - attributetype: 'attributeType', - basefrequency: 'baseFrequency', - baseprofile: 'baseProfile', - calcmode: 'calcMode', - clippathunits: 'clipPathUnits', - diffuseconstant: 'diffuseConstant', - edgemode: 'edgeMode', - filterunits: 'filterUnits', - glyphref: 'glyphRef', - gradienttransform: 'gradientTransform', - gradientunits: 'gradientUnits', - kernelmatrix: 'kernelMatrix', - kernelunitlength: 'kernelUnitLength', - keypoints: 'keyPoints', - keysplines: 'keySplines', - keytimes: 'keyTimes', - lengthadjust: 'lengthAdjust', - limitingconeangle: 'limitingConeAngle', - markerheight: 'markerHeight', - markerunits: 'markerUnits', - markerwidth: 'markerWidth', - maskcontentunits: 'maskContentUnits', - maskunits: 'maskUnits', - numoctaves: 'numOctaves', - pathlength: 'pathLength', - patterncontentunits: 'patternContentUnits', - patterntransform: 'patternTransform', - patternunits: 'patternUnits', - pointsatx: 'pointsAtX', - pointsaty: 'pointsAtY', - pointsatz: 'pointsAtZ', - preservealpha: 'preserveAlpha', - preserveaspectratio: 'preserveAspectRatio', - primitiveunits: 'primitiveUnits', - refx: 'refX', - refy: 'refY', - repeatcount: 'repeatCount', - repeatdur: 'repeatDur', - requiredextensions: 'requiredExtensions', - requiredfeatures: 'requiredFeatures', - specularconstant: 'specularConstant', - specularexponent: 'specularExponent', - spreadmethod: 'spreadMethod', - startoffset: 'startOffset', - stddeviation: 'stdDeviation', - stitchtiles: 'stitchTiles', - surfacescale: 'surfaceScale', - systemlanguage: 'systemLanguage', - tablevalues: 'tableValues', - targetx: 'targetX', - targety: 'targetY', - textlength: 'textLength', - viewbox: 'viewBox', - viewtarget: 'viewTarget', - xchannelselector: 'xChannelSelector', - ychannelselector: 'yChannelSelector', - zoomandpan: 'zoomAndPan' -}; - -const XML_ATTRS_ADJUSTMENT_MAP = { - 'xlink:actuate': { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK }, - 'xlink:arcrole': { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK }, - 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK }, - 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK }, - 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK }, - 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK }, - 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK }, - 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML }, - 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML }, - 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML }, - xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS }, - 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS } -}; - -//SVG tag names adjustment map -const SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = { - altglyph: 'altGlyph', - altglyphdef: 'altGlyphDef', - altglyphitem: 'altGlyphItem', - animatecolor: 'animateColor', - animatemotion: 'animateMotion', - animatetransform: 'animateTransform', - clippath: 'clipPath', - feblend: 'feBlend', - fecolormatrix: 'feColorMatrix', - fecomponenttransfer: 'feComponentTransfer', - fecomposite: 'feComposite', - feconvolvematrix: 'feConvolveMatrix', - fediffuselighting: 'feDiffuseLighting', - fedisplacementmap: 'feDisplacementMap', - fedistantlight: 'feDistantLight', - feflood: 'feFlood', - fefunca: 'feFuncA', - fefuncb: 'feFuncB', - fefuncg: 'feFuncG', - fefuncr: 'feFuncR', - fegaussianblur: 'feGaussianBlur', - feimage: 'feImage', - femerge: 'feMerge', - femergenode: 'feMergeNode', - femorphology: 'feMorphology', - feoffset: 'feOffset', - fepointlight: 'fePointLight', - fespecularlighting: 'feSpecularLighting', - fespotlight: 'feSpotLight', - fetile: 'feTile', - feturbulence: 'feTurbulence', - foreignobject: 'foreignObject', - glyphref: 'glyphRef', - lineargradient: 'linearGradient', - radialgradient: 'radialGradient', - textpath: 'textPath' -}); - -//Tags that causes exit from foreign content -const EXITS_FOREIGN_CONTENT = { - [$.B]: true, - [$.BIG]: true, - [$.BLOCKQUOTE]: true, - [$.BODY]: true, - [$.BR]: true, - [$.CENTER]: true, - [$.CODE]: true, - [$.DD]: true, - [$.DIV]: true, - [$.DL]: true, - [$.DT]: true, - [$.EM]: true, - [$.EMBED]: true, - [$.H1]: true, - [$.H2]: true, - [$.H3]: true, - [$.H4]: true, - [$.H5]: true, - [$.H6]: true, - [$.HEAD]: true, - [$.HR]: true, - [$.I]: true, - [$.IMG]: true, - [$.LI]: true, - [$.LISTING]: true, - [$.MENU]: true, - [$.META]: true, - [$.NOBR]: true, - [$.OL]: true, - [$.P]: true, - [$.PRE]: true, - [$.RUBY]: true, - [$.S]: true, - [$.SMALL]: true, - [$.SPAN]: true, - [$.STRONG]: true, - [$.STRIKE]: true, - [$.SUB]: true, - [$.SUP]: true, - [$.TABLE]: true, - [$.TT]: true, - [$.U]: true, - [$.UL]: true, - [$.VAR]: true -}; - -//Check exit from foreign content -exports.causesExit = function(startTagToken) { - const tn = startTagToken.tagName; - const isFontWithAttrs = - tn === $.FONT && - (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null || - Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null || - Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null); + if (hasPrefix(publicId, prefixes)) { + return DOCUMENT_MODE.QUIRKS + } - return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn]; -}; + prefixes = + systemId === null + ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES + : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES -//Token adjustments -exports.adjustTokenMathMLAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - if (token.attrs[i].name === DEFINITION_URL_ATTR) { - token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; - break; + if (hasPrefix(publicId, prefixes)) { + return DOCUMENT_MODE.LIMITED_QUIRKS + } } - } -}; -exports.adjustTokenSVGAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; + return DOCUMENT_MODE.NO_QUIRKS + } + + exports.serializeContent = function (name, publicId, systemId) { + let str = '!DOCTYPE ' - if (adjustedAttrName) { - token.attrs[i].name = adjustedAttrName; + if (name) { + str += name } - } -}; -exports.adjustTokenXMLAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; + if (publicId) { + str += ' PUBLIC ' + enquoteDoctypeId(publicId) + } else if (systemId) { + str += ' SYSTEM' + } - if (adjustedAttrEntry) { - token.attrs[i].prefix = adjustedAttrEntry.prefix; - token.attrs[i].name = adjustedAttrEntry.name; - token.attrs[i].namespace = adjustedAttrEntry.namespace; + if (systemId !== null) { + str += ' ' + enquoteDoctypeId(systemId) } - } -}; -exports.adjustTokenSVGTagName = function(token) { - const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName]; + return str + } - if (adjustedTagName) { - token.tagName = adjustedTagName; - } -}; + /***/ + }, -//Integration points -function isMathMLTextIntegrationPoint(tn, ns) { - return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT); -} + /***/ 4068: /***/ (module) => { + 'use strict' + + module.exports = { + controlCharacterInInputStream: 'control-character-in-input-stream', + noncharacterInInputStream: 'noncharacter-in-input-stream', + surrogateInInputStream: 'surrogate-in-input-stream', + nonVoidHtmlElementStartTagWithTrailingSolidus: + 'non-void-html-element-start-tag-with-trailing-solidus', + endTagWithAttributes: 'end-tag-with-attributes', + endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus', + unexpectedSolidusInTag: 'unexpected-solidus-in-tag', + unexpectedNullCharacter: 'unexpected-null-character', + unexpectedQuestionMarkInsteadOfTagName: + 'unexpected-question-mark-instead-of-tag-name', + invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name', + unexpectedEqualsSignBeforeAttributeName: + 'unexpected-equals-sign-before-attribute-name', + missingEndTagName: 'missing-end-tag-name', + unexpectedCharacterInAttributeName: + 'unexpected-character-in-attribute-name', + unknownNamedCharacterReference: 'unknown-named-character-reference', + missingSemicolonAfterCharacterReference: + 'missing-semicolon-after-character-reference', + unexpectedCharacterAfterDoctypeSystemIdentifier: + 'unexpected-character-after-doctype-system-identifier', + unexpectedCharacterInUnquotedAttributeValue: + 'unexpected-character-in-unquoted-attribute-value', + eofBeforeTagName: 'eof-before-tag-name', + eofInTag: 'eof-in-tag', + missingAttributeValue: 'missing-attribute-value', + missingWhitespaceBetweenAttributes: + 'missing-whitespace-between-attributes', + missingWhitespaceAfterDoctypePublicKeyword: + 'missing-whitespace-after-doctype-public-keyword', + missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: + 'missing-whitespace-between-doctype-public-and-system-identifiers', + missingWhitespaceAfterDoctypeSystemKeyword: + 'missing-whitespace-after-doctype-system-keyword', + missingQuoteBeforeDoctypePublicIdentifier: + 'missing-quote-before-doctype-public-identifier', + missingQuoteBeforeDoctypeSystemIdentifier: + 'missing-quote-before-doctype-system-identifier', + missingDoctypePublicIdentifier: 'missing-doctype-public-identifier', + missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier', + abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier', + abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier', + cdataInHtmlContent: 'cdata-in-html-content', + incorrectlyOpenedComment: 'incorrectly-opened-comment', + eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text', + eofInDoctype: 'eof-in-doctype', + nestedComment: 'nested-comment', + abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment', + eofInComment: 'eof-in-comment', + incorrectlyClosedComment: 'incorrectly-closed-comment', + eofInCdata: 'eof-in-cdata', + absenceOfDigitsInNumericCharacterReference: + 'absence-of-digits-in-numeric-character-reference', + nullCharacterReference: 'null-character-reference', + surrogateCharacterReference: 'surrogate-character-reference', + characterReferenceOutsideUnicodeRange: + 'character-reference-outside-unicode-range', + controlCharacterReference: 'control-character-reference', + noncharacterCharacterReference: 'noncharacter-character-reference', + missingWhitespaceBeforeDoctypeName: + 'missing-whitespace-before-doctype-name', + missingDoctypeName: 'missing-doctype-name', + invalidCharacterSequenceAfterDoctypeName: + 'invalid-character-sequence-after-doctype-name', + duplicateAttribute: 'duplicate-attribute', + nonConformingDoctype: 'non-conforming-doctype', + missingDoctype: 'missing-doctype', + misplacedDoctype: 'misplaced-doctype', + endTagWithoutMatchingOpenElement: + 'end-tag-without-matching-open-element', + closingOfElementWithOpenChildElements: + 'closing-of-element-with-open-child-elements', + disallowedContentInNoscriptInHead: + 'disallowed-content-in-noscript-in-head', + openElementsLeftAfterEof: 'open-elements-left-after-eof', + abandonedHeadElementChild: 'abandoned-head-element-child', + misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element', + nestedNoscriptInHead: 'nested-noscript-in-head', + eofInElementThatCanContainOnlyText: + 'eof-in-element-that-can-contain-only-text' + } -function isHtmlIntegrationPoint(tn, ns, attrs) { - if (ns === NS.MATHML && tn === $.ANNOTATION_XML) { - for (let i = 0; i < attrs.length; i++) { - if (attrs[i].name === ATTRS.ENCODING) { - const value = attrs[i].value.toLowerCase(); + /***/ + }, - return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; - } - } - } + /***/ 4183: /***/ ( + __unused_webpack_module, + exports, + __webpack_require__ + ) => { + 'use strict' + + const Tokenizer = __webpack_require__(6386) + const HTML = __webpack_require__(4734) + + //Aliases + const $ = HTML.TAG_NAMES + const NS = HTML.NAMESPACES + const ATTRS = HTML.ATTRS + + //MIME types + const MIME_TYPES = { + TEXT_HTML: 'text/html', + APPLICATION_XML: 'application/xhtml+xml' + } - return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE); -} + //Attributes + const DEFINITION_URL_ATTR = 'definitionurl' + const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL' + const SVG_ATTRS_ADJUSTMENT_MAP = { + attributename: 'attributeName', + attributetype: 'attributeType', + basefrequency: 'baseFrequency', + baseprofile: 'baseProfile', + calcmode: 'calcMode', + clippathunits: 'clipPathUnits', + diffuseconstant: 'diffuseConstant', + edgemode: 'edgeMode', + filterunits: 'filterUnits', + glyphref: 'glyphRef', + gradienttransform: 'gradientTransform', + gradientunits: 'gradientUnits', + kernelmatrix: 'kernelMatrix', + kernelunitlength: 'kernelUnitLength', + keypoints: 'keyPoints', + keysplines: 'keySplines', + keytimes: 'keyTimes', + lengthadjust: 'lengthAdjust', + limitingconeangle: 'limitingConeAngle', + markerheight: 'markerHeight', + markerunits: 'markerUnits', + markerwidth: 'markerWidth', + maskcontentunits: 'maskContentUnits', + maskunits: 'maskUnits', + numoctaves: 'numOctaves', + pathlength: 'pathLength', + patterncontentunits: 'patternContentUnits', + patterntransform: 'patternTransform', + patternunits: 'patternUnits', + pointsatx: 'pointsAtX', + pointsaty: 'pointsAtY', + pointsatz: 'pointsAtZ', + preservealpha: 'preserveAlpha', + preserveaspectratio: 'preserveAspectRatio', + primitiveunits: 'primitiveUnits', + refx: 'refX', + refy: 'refY', + repeatcount: 'repeatCount', + repeatdur: 'repeatDur', + requiredextensions: 'requiredExtensions', + requiredfeatures: 'requiredFeatures', + specularconstant: 'specularConstant', + specularexponent: 'specularExponent', + spreadmethod: 'spreadMethod', + startoffset: 'startOffset', + stddeviation: 'stdDeviation', + stitchtiles: 'stitchTiles', + surfacescale: 'surfaceScale', + systemlanguage: 'systemLanguage', + tablevalues: 'tableValues', + targetx: 'targetX', + targety: 'targetY', + textlength: 'textLength', + viewbox: 'viewBox', + viewtarget: 'viewTarget', + xchannelselector: 'xChannelSelector', + ychannelselector: 'yChannelSelector', + zoomandpan: 'zoomAndPan' + } -exports.isIntegrationPoint = function(tn, ns, attrs, foreignNS) { - if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) { - return true; - } + const XML_ATTRS_ADJUSTMENT_MAP = { + 'xlink:actuate': { + prefix: 'xlink', + name: 'actuate', + namespace: NS.XLINK + }, + 'xlink:arcrole': { + prefix: 'xlink', + name: 'arcrole', + namespace: NS.XLINK + }, + 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK }, + 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK }, + 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK }, + 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK }, + 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK }, + 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML }, + 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML }, + 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML }, + xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS }, + 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS } + } - if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)) { - return true; - } + //SVG tag names adjustment map + const SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = { + altglyph: 'altGlyph', + altglyphdef: 'altGlyphDef', + altglyphitem: 'altGlyphItem', + animatecolor: 'animateColor', + animatemotion: 'animateMotion', + animatetransform: 'animateTransform', + clippath: 'clipPath', + feblend: 'feBlend', + fecolormatrix: 'feColorMatrix', + fecomponenttransfer: 'feComponentTransfer', + fecomposite: 'feComposite', + feconvolvematrix: 'feConvolveMatrix', + fediffuselighting: 'feDiffuseLighting', + fedisplacementmap: 'feDisplacementMap', + fedistantlight: 'feDistantLight', + feflood: 'feFlood', + fefunca: 'feFuncA', + fefuncb: 'feFuncB', + fefuncg: 'feFuncG', + fefuncr: 'feFuncR', + fegaussianblur: 'feGaussianBlur', + feimage: 'feImage', + femerge: 'feMerge', + femergenode: 'feMergeNode', + femorphology: 'feMorphology', + feoffset: 'feOffset', + fepointlight: 'fePointLight', + fespecularlighting: 'feSpecularLighting', + fespotlight: 'feSpotLight', + fetile: 'feTile', + feturbulence: 'feTurbulence', + foreignobject: 'foreignObject', + glyphref: 'glyphRef', + lineargradient: 'linearGradient', + radialgradient: 'radialGradient', + textpath: 'textPath' + }) - return false; -}; - - -/***/ }), - -/***/ 4734: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const NS = (exports.NAMESPACES = { - HTML: 'http://www.w3.org/1999/xhtml', - MATHML: 'http://www.w3.org/1998/Math/MathML', - SVG: 'http://www.w3.org/2000/svg', - XLINK: 'http://www.w3.org/1999/xlink', - XML: 'http://www.w3.org/XML/1998/namespace', - XMLNS: 'http://www.w3.org/2000/xmlns/' -}); - -exports.ATTRS = { - TYPE: 'type', - ACTION: 'action', - ENCODING: 'encoding', - PROMPT: 'prompt', - NAME: 'name', - COLOR: 'color', - FACE: 'face', - SIZE: 'size' -}; - -exports.DOCUMENT_MODE = { - NO_QUIRKS: 'no-quirks', - QUIRKS: 'quirks', - LIMITED_QUIRKS: 'limited-quirks' -}; - -const $ = (exports.TAG_NAMES = { - A: 'a', - ADDRESS: 'address', - ANNOTATION_XML: 'annotation-xml', - APPLET: 'applet', - AREA: 'area', - ARTICLE: 'article', - ASIDE: 'aside', - - B: 'b', - BASE: 'base', - BASEFONT: 'basefont', - BGSOUND: 'bgsound', - BIG: 'big', - BLOCKQUOTE: 'blockquote', - BODY: 'body', - BR: 'br', - BUTTON: 'button', - - CAPTION: 'caption', - CENTER: 'center', - CODE: 'code', - COL: 'col', - COLGROUP: 'colgroup', - - DD: 'dd', - DESC: 'desc', - DETAILS: 'details', - DIALOG: 'dialog', - DIR: 'dir', - DIV: 'div', - DL: 'dl', - DT: 'dt', - - EM: 'em', - EMBED: 'embed', - - FIELDSET: 'fieldset', - FIGCAPTION: 'figcaption', - FIGURE: 'figure', - FONT: 'font', - FOOTER: 'footer', - FOREIGN_OBJECT: 'foreignObject', - FORM: 'form', - FRAME: 'frame', - FRAMESET: 'frameset', - - H1: 'h1', - H2: 'h2', - H3: 'h3', - H4: 'h4', - H5: 'h5', - H6: 'h6', - HEAD: 'head', - HEADER: 'header', - HGROUP: 'hgroup', - HR: 'hr', - HTML: 'html', - - I: 'i', - IMG: 'img', - IMAGE: 'image', - INPUT: 'input', - IFRAME: 'iframe', - - KEYGEN: 'keygen', - - LABEL: 'label', - LI: 'li', - LINK: 'link', - LISTING: 'listing', - - MAIN: 'main', - MALIGNMARK: 'malignmark', - MARQUEE: 'marquee', - MATH: 'math', - MENU: 'menu', - META: 'meta', - MGLYPH: 'mglyph', - MI: 'mi', - MO: 'mo', - MN: 'mn', - MS: 'ms', - MTEXT: 'mtext', - - NAV: 'nav', - NOBR: 'nobr', - NOFRAMES: 'noframes', - NOEMBED: 'noembed', - NOSCRIPT: 'noscript', - - OBJECT: 'object', - OL: 'ol', - OPTGROUP: 'optgroup', - OPTION: 'option', - - P: 'p', - PARAM: 'param', - PLAINTEXT: 'plaintext', - PRE: 'pre', - - RB: 'rb', - RP: 'rp', - RT: 'rt', - RTC: 'rtc', - RUBY: 'ruby', - - S: 's', - SCRIPT: 'script', - SECTION: 'section', - SELECT: 'select', - SOURCE: 'source', - SMALL: 'small', - SPAN: 'span', - STRIKE: 'strike', - STRONG: 'strong', - STYLE: 'style', - SUB: 'sub', - SUMMARY: 'summary', - SUP: 'sup', - - TABLE: 'table', - TBODY: 'tbody', - TEMPLATE: 'template', - TEXTAREA: 'textarea', - TFOOT: 'tfoot', - TD: 'td', - TH: 'th', - THEAD: 'thead', - TITLE: 'title', - TR: 'tr', - TRACK: 'track', - TT: 'tt', - - U: 'u', - UL: 'ul', - - SVG: 'svg', - - VAR: 'var', - - WBR: 'wbr', - - XMP: 'xmp' -}); - -exports.SPECIAL_ELEMENTS = { - [NS.HTML]: { - [$.ADDRESS]: true, - [$.APPLET]: true, - [$.AREA]: true, - [$.ARTICLE]: true, - [$.ASIDE]: true, - [$.BASE]: true, - [$.BASEFONT]: true, - [$.BGSOUND]: true, + //Tags that causes exit from foreign content + const EXITS_FOREIGN_CONTENT = { + [$.B]: true, + [$.BIG]: true, [$.BLOCKQUOTE]: true, [$.BODY]: true, [$.BR]: true, - [$.BUTTON]: true, - [$.CAPTION]: true, [$.CENTER]: true, - [$.COL]: true, - [$.COLGROUP]: true, + [$.CODE]: true, [$.DD]: true, - [$.DETAILS]: true, - [$.DIR]: true, [$.DIV]: true, [$.DL]: true, [$.DT]: true, + [$.EM]: true, [$.EMBED]: true, - [$.FIELDSET]: true, - [$.FIGCAPTION]: true, - [$.FIGURE]: true, - [$.FOOTER]: true, - [$.FORM]: true, - [$.FRAME]: true, - [$.FRAMESET]: true, [$.H1]: true, [$.H2]: true, [$.H3]: true, @@ -5125,19009 +5558,39554 @@ exports.SPECIAL_ELEMENTS = { [$.H5]: true, [$.H6]: true, [$.HEAD]: true, - [$.HEADER]: true, - [$.HGROUP]: true, [$.HR]: true, - [$.HTML]: true, - [$.IFRAME]: true, + [$.I]: true, [$.IMG]: true, - [$.INPUT]: true, [$.LI]: true, - [$.LINK]: true, [$.LISTING]: true, - [$.MAIN]: true, - [$.MARQUEE]: true, [$.MENU]: true, [$.META]: true, - [$.NAV]: true, - [$.NOEMBED]: true, - [$.NOFRAMES]: true, - [$.NOSCRIPT]: true, - [$.OBJECT]: true, + [$.NOBR]: true, [$.OL]: true, [$.P]: true, - [$.PARAM]: true, - [$.PLAINTEXT]: true, [$.PRE]: true, - [$.SCRIPT]: true, - [$.SECTION]: true, - [$.SELECT]: true, - [$.SOURCE]: true, - [$.STYLE]: true, - [$.SUMMARY]: true, + [$.RUBY]: true, + [$.S]: true, + [$.SMALL]: true, + [$.SPAN]: true, + [$.STRONG]: true, + [$.STRIKE]: true, + [$.SUB]: true, + [$.SUP]: true, [$.TABLE]: true, - [$.TBODY]: true, - [$.TD]: true, - [$.TEMPLATE]: true, - [$.TEXTAREA]: true, - [$.TFOOT]: true, - [$.TH]: true, - [$.THEAD]: true, - [$.TITLE]: true, - [$.TR]: true, - [$.TRACK]: true, + [$.TT]: true, + [$.U]: true, [$.UL]: true, - [$.WBR]: true, - [$.XMP]: true - }, - [NS.MATHML]: { - [$.MI]: true, - [$.MO]: true, - [$.MN]: true, - [$.MS]: true, - [$.MTEXT]: true, - [$.ANNOTATION_XML]: true - }, - [NS.SVG]: { - [$.TITLE]: true, - [$.FOREIGN_OBJECT]: true, - [$.DESC]: true - } -}; - - -/***/ }), - -/***/ 118: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const UNDEFINED_CODE_POINTS = [ - 0xfffe, - 0xffff, - 0x1fffe, - 0x1ffff, - 0x2fffe, - 0x2ffff, - 0x3fffe, - 0x3ffff, - 0x4fffe, - 0x4ffff, - 0x5fffe, - 0x5ffff, - 0x6fffe, - 0x6ffff, - 0x7fffe, - 0x7ffff, - 0x8fffe, - 0x8ffff, - 0x9fffe, - 0x9ffff, - 0xafffe, - 0xaffff, - 0xbfffe, - 0xbffff, - 0xcfffe, - 0xcffff, - 0xdfffe, - 0xdffff, - 0xefffe, - 0xeffff, - 0xffffe, - 0xfffff, - 0x10fffe, - 0x10ffff -]; - -exports.REPLACEMENT_CHARACTER = '\uFFFD'; - -exports.CODE_POINTS = { - EOF: -1, - NULL: 0x00, - TABULATION: 0x09, - CARRIAGE_RETURN: 0x0d, - LINE_FEED: 0x0a, - FORM_FEED: 0x0c, - SPACE: 0x20, - EXCLAMATION_MARK: 0x21, - QUOTATION_MARK: 0x22, - NUMBER_SIGN: 0x23, - AMPERSAND: 0x26, - APOSTROPHE: 0x27, - HYPHEN_MINUS: 0x2d, - SOLIDUS: 0x2f, - DIGIT_0: 0x30, - DIGIT_9: 0x39, - SEMICOLON: 0x3b, - LESS_THAN_SIGN: 0x3c, - EQUALS_SIGN: 0x3d, - GREATER_THAN_SIGN: 0x3e, - QUESTION_MARK: 0x3f, - LATIN_CAPITAL_A: 0x41, - LATIN_CAPITAL_F: 0x46, - LATIN_CAPITAL_X: 0x58, - LATIN_CAPITAL_Z: 0x5a, - RIGHT_SQUARE_BRACKET: 0x5d, - GRAVE_ACCENT: 0x60, - LATIN_SMALL_A: 0x61, - LATIN_SMALL_F: 0x66, - LATIN_SMALL_X: 0x78, - LATIN_SMALL_Z: 0x7a, - REPLACEMENT_CHARACTER: 0xfffd -}; - -exports.CODE_POINT_SEQUENCES = { - DASH_DASH_STRING: [0x2d, 0x2d], //-- - DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE - CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[ - SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script - PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC - SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM -}; - -//Surrogates -exports.isSurrogate = function(cp) { - return cp >= 0xd800 && cp <= 0xdfff; -}; - -exports.isSurrogatePair = function(cp) { - return cp >= 0xdc00 && cp <= 0xdfff; -}; - -exports.getSurrogatePairCodePoint = function(cp1, cp2) { - return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2; -}; - -//NOTE: excluding NULL and ASCII whitespace -exports.isControlCodePoint = function(cp) { - return ( - (cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || - (cp >= 0x7f && cp <= 0x9f) - ); -}; - -exports.isUndefinedCodePoint = function(cp) { - return (cp >= 0xfdd0 && cp <= 0xfdef) || UNDEFINED_CODE_POINTS.indexOf(cp) > -1; -}; - - -/***/ }), - -/***/ 1842: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const Mixin = __webpack_require__(369); - -class ErrorReportingMixinBase extends Mixin { - constructor(host, opts) { - super(host); - - this.posTracker = null; - this.onParseError = opts.onParseError; - } + [$.VAR]: true + } - _setErrorLocation(err) { - err.startLine = err.endLine = this.posTracker.line; - err.startCol = err.endCol = this.posTracker.col; - err.startOffset = err.endOffset = this.posTracker.offset; - } + //Check exit from foreign content + exports.causesExit = function (startTagToken) { + const tn = startTagToken.tagName + const isFontWithAttrs = + tn === $.FONT && + (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null || + Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null || + Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null) - _reportError(code) { - const err = { - code: code, - startLine: -1, - startCol: -1, - startOffset: -1, - endLine: -1, - endCol: -1, - endOffset: -1 - }; + return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn] + } - this._setErrorLocation(err); - this.onParseError(err); - } + //Token adjustments + exports.adjustTokenMathMLAttrs = function (token) { + for (let i = 0; i < token.attrs.length; i++) { + if (token.attrs[i].name === DEFINITION_URL_ATTR) { + token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR + break + } + } + } - _getOverriddenMethods(mxn) { - return { - _err(code) { - mxn._reportError(code); + exports.adjustTokenSVGAttrs = function (token) { + for (let i = 0; i < token.attrs.length; i++) { + const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name] + + if (adjustedAttrName) { + token.attrs[i].name = adjustedAttrName + } + } + } + + exports.adjustTokenXMLAttrs = function (token) { + for (let i = 0; i < token.attrs.length; i++) { + const adjustedAttrEntry = + XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name] + + if (adjustedAttrEntry) { + token.attrs[i].prefix = adjustedAttrEntry.prefix + token.attrs[i].name = adjustedAttrEntry.name + token.attrs[i].namespace = adjustedAttrEntry.namespace + } + } + } + + exports.adjustTokenSVGTagName = function (token) { + const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName] + + if (adjustedTagName) { + token.tagName = adjustedTagName + } + } + + //Integration points + function isMathMLTextIntegrationPoint(tn, ns) { + return ( + ns === NS.MATHML && + (tn === $.MI || + tn === $.MO || + tn === $.MN || + tn === $.MS || + tn === $.MTEXT) + ) + } + + function isHtmlIntegrationPoint(tn, ns, attrs) { + if (ns === NS.MATHML && tn === $.ANNOTATION_XML) { + for (let i = 0; i < attrs.length; i++) { + if (attrs[i].name === ATTRS.ENCODING) { + const value = attrs[i].value.toLowerCase() + + return ( + value === MIME_TYPES.TEXT_HTML || + value === MIME_TYPES.APPLICATION_XML + ) } - }; - } -} + } + } -module.exports = ErrorReportingMixinBase; + return ( + ns === NS.SVG && + (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE) + ) + } + exports.isIntegrationPoint = function (tn, ns, attrs, foreignNS) { + if ( + (!foreignNS || foreignNS === NS.HTML) && + isHtmlIntegrationPoint(tn, ns, attrs) + ) { + return true + } -/***/ }), + if ( + (!foreignNS || foreignNS === NS.MATHML) && + isMathMLTextIntegrationPoint(tn, ns) + ) { + return true + } -/***/ 9203: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return false + } -"use strict"; + /***/ + }, + /***/ 4734: /***/ (__unused_webpack_module, exports) => { + 'use strict' -const ErrorReportingMixinBase = __webpack_require__(1842); -const ErrorReportingTokenizerMixin = __webpack_require__(6378); -const LocationInfoTokenizerMixin = __webpack_require__(6091); -const Mixin = __webpack_require__(369); + const NS = (exports.NAMESPACES = { + HTML: 'http://www.w3.org/1999/xhtml', + MATHML: 'http://www.w3.org/1998/Math/MathML', + SVG: 'http://www.w3.org/2000/svg', + XLINK: 'http://www.w3.org/1999/xlink', + XML: 'http://www.w3.org/XML/1998/namespace', + XMLNS: 'http://www.w3.org/2000/xmlns/' + }) -class ErrorReportingParserMixin extends ErrorReportingMixinBase { - constructor(parser, opts) { - super(parser, opts); + exports.ATTRS = { + TYPE: 'type', + ACTION: 'action', + ENCODING: 'encoding', + PROMPT: 'prompt', + NAME: 'name', + COLOR: 'color', + FACE: 'face', + SIZE: 'size' + } - this.opts = opts; - this.ctLoc = null; - this.locBeforeToken = false; - } + exports.DOCUMENT_MODE = { + NO_QUIRKS: 'no-quirks', + QUIRKS: 'quirks', + LIMITED_QUIRKS: 'limited-quirks' + } - _setErrorLocation(err) { - if (this.ctLoc) { - err.startLine = this.ctLoc.startLine; - err.startCol = this.ctLoc.startCol; - err.startOffset = this.ctLoc.startOffset; + const $ = (exports.TAG_NAMES = { + A: 'a', + ADDRESS: 'address', + ANNOTATION_XML: 'annotation-xml', + APPLET: 'applet', + AREA: 'area', + ARTICLE: 'article', + ASIDE: 'aside', + + B: 'b', + BASE: 'base', + BASEFONT: 'basefont', + BGSOUND: 'bgsound', + BIG: 'big', + BLOCKQUOTE: 'blockquote', + BODY: 'body', + BR: 'br', + BUTTON: 'button', + + CAPTION: 'caption', + CENTER: 'center', + CODE: 'code', + COL: 'col', + COLGROUP: 'colgroup', + + DD: 'dd', + DESC: 'desc', + DETAILS: 'details', + DIALOG: 'dialog', + DIR: 'dir', + DIV: 'div', + DL: 'dl', + DT: 'dt', + + EM: 'em', + EMBED: 'embed', + + FIELDSET: 'fieldset', + FIGCAPTION: 'figcaption', + FIGURE: 'figure', + FONT: 'font', + FOOTER: 'footer', + FOREIGN_OBJECT: 'foreignObject', + FORM: 'form', + FRAME: 'frame', + FRAMESET: 'frameset', + + H1: 'h1', + H2: 'h2', + H3: 'h3', + H4: 'h4', + H5: 'h5', + H6: 'h6', + HEAD: 'head', + HEADER: 'header', + HGROUP: 'hgroup', + HR: 'hr', + HTML: 'html', + + I: 'i', + IMG: 'img', + IMAGE: 'image', + INPUT: 'input', + IFRAME: 'iframe', + + KEYGEN: 'keygen', + + LABEL: 'label', + LI: 'li', + LINK: 'link', + LISTING: 'listing', + + MAIN: 'main', + MALIGNMARK: 'malignmark', + MARQUEE: 'marquee', + MATH: 'math', + MENU: 'menu', + META: 'meta', + MGLYPH: 'mglyph', + MI: 'mi', + MO: 'mo', + MN: 'mn', + MS: 'ms', + MTEXT: 'mtext', + + NAV: 'nav', + NOBR: 'nobr', + NOFRAMES: 'noframes', + NOEMBED: 'noembed', + NOSCRIPT: 'noscript', + + OBJECT: 'object', + OL: 'ol', + OPTGROUP: 'optgroup', + OPTION: 'option', + + P: 'p', + PARAM: 'param', + PLAINTEXT: 'plaintext', + PRE: 'pre', + + RB: 'rb', + RP: 'rp', + RT: 'rt', + RTC: 'rtc', + RUBY: 'ruby', + + S: 's', + SCRIPT: 'script', + SECTION: 'section', + SELECT: 'select', + SOURCE: 'source', + SMALL: 'small', + SPAN: 'span', + STRIKE: 'strike', + STRONG: 'strong', + STYLE: 'style', + SUB: 'sub', + SUMMARY: 'summary', + SUP: 'sup', + + TABLE: 'table', + TBODY: 'tbody', + TEMPLATE: 'template', + TEXTAREA: 'textarea', + TFOOT: 'tfoot', + TD: 'td', + TH: 'th', + THEAD: 'thead', + TITLE: 'title', + TR: 'tr', + TRACK: 'track', + TT: 'tt', + + U: 'u', + UL: 'ul', + + SVG: 'svg', + + VAR: 'var', + + WBR: 'wbr', + + XMP: 'xmp' + }) - err.endLine = this.locBeforeToken ? this.ctLoc.startLine : this.ctLoc.endLine; - err.endCol = this.locBeforeToken ? this.ctLoc.startCol : this.ctLoc.endCol; - err.endOffset = this.locBeforeToken ? this.ctLoc.startOffset : this.ctLoc.endOffset; + exports.SPECIAL_ELEMENTS = { + [NS.HTML]: { + [$.ADDRESS]: true, + [$.APPLET]: true, + [$.AREA]: true, + [$.ARTICLE]: true, + [$.ASIDE]: true, + [$.BASE]: true, + [$.BASEFONT]: true, + [$.BGSOUND]: true, + [$.BLOCKQUOTE]: true, + [$.BODY]: true, + [$.BR]: true, + [$.BUTTON]: true, + [$.CAPTION]: true, + [$.CENTER]: true, + [$.COL]: true, + [$.COLGROUP]: true, + [$.DD]: true, + [$.DETAILS]: true, + [$.DIR]: true, + [$.DIV]: true, + [$.DL]: true, + [$.DT]: true, + [$.EMBED]: true, + [$.FIELDSET]: true, + [$.FIGCAPTION]: true, + [$.FIGURE]: true, + [$.FOOTER]: true, + [$.FORM]: true, + [$.FRAME]: true, + [$.FRAMESET]: true, + [$.H1]: true, + [$.H2]: true, + [$.H3]: true, + [$.H4]: true, + [$.H5]: true, + [$.H6]: true, + [$.HEAD]: true, + [$.HEADER]: true, + [$.HGROUP]: true, + [$.HR]: true, + [$.HTML]: true, + [$.IFRAME]: true, + [$.IMG]: true, + [$.INPUT]: true, + [$.LI]: true, + [$.LINK]: true, + [$.LISTING]: true, + [$.MAIN]: true, + [$.MARQUEE]: true, + [$.MENU]: true, + [$.META]: true, + [$.NAV]: true, + [$.NOEMBED]: true, + [$.NOFRAMES]: true, + [$.NOSCRIPT]: true, + [$.OBJECT]: true, + [$.OL]: true, + [$.P]: true, + [$.PARAM]: true, + [$.PLAINTEXT]: true, + [$.PRE]: true, + [$.SCRIPT]: true, + [$.SECTION]: true, + [$.SELECT]: true, + [$.SOURCE]: true, + [$.STYLE]: true, + [$.SUMMARY]: true, + [$.TABLE]: true, + [$.TBODY]: true, + [$.TD]: true, + [$.TEMPLATE]: true, + [$.TEXTAREA]: true, + [$.TFOOT]: true, + [$.TH]: true, + [$.THEAD]: true, + [$.TITLE]: true, + [$.TR]: true, + [$.TRACK]: true, + [$.UL]: true, + [$.WBR]: true, + [$.XMP]: true + }, + [NS.MATHML]: { + [$.MI]: true, + [$.MO]: true, + [$.MN]: true, + [$.MS]: true, + [$.MTEXT]: true, + [$.ANNOTATION_XML]: true + }, + [NS.SVG]: { + [$.TITLE]: true, + [$.FOREIGN_OBJECT]: true, + [$.DESC]: true } - } + } - _getOverriddenMethods(mxn, orig) { - return { - _bootstrap(document, fragmentContext) { - orig._bootstrap.call(this, document, fragmentContext); + /***/ + }, - Mixin.install(this.tokenizer, ErrorReportingTokenizerMixin, mxn.opts); - Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); - }, + /***/ 118: /***/ (__unused_webpack_module, exports) => { + 'use strict' + + const UNDEFINED_CODE_POINTS = [ + 0xfffe, + 0xffff, + 0x1fffe, + 0x1ffff, + 0x2fffe, + 0x2ffff, + 0x3fffe, + 0x3ffff, + 0x4fffe, + 0x4ffff, + 0x5fffe, + 0x5ffff, + 0x6fffe, + 0x6ffff, + 0x7fffe, + 0x7ffff, + 0x8fffe, + 0x8ffff, + 0x9fffe, + 0x9ffff, + 0xafffe, + 0xaffff, + 0xbfffe, + 0xbffff, + 0xcfffe, + 0xcffff, + 0xdfffe, + 0xdffff, + 0xefffe, + 0xeffff, + 0xffffe, + 0xfffff, + 0x10fffe, + 0x10ffff + ] + + exports.REPLACEMENT_CHARACTER = '\uFFFD' + + exports.CODE_POINTS = { + EOF: -1, + NULL: 0x00, + TABULATION: 0x09, + CARRIAGE_RETURN: 0x0d, + LINE_FEED: 0x0a, + FORM_FEED: 0x0c, + SPACE: 0x20, + EXCLAMATION_MARK: 0x21, + QUOTATION_MARK: 0x22, + NUMBER_SIGN: 0x23, + AMPERSAND: 0x26, + APOSTROPHE: 0x27, + HYPHEN_MINUS: 0x2d, + SOLIDUS: 0x2f, + DIGIT_0: 0x30, + DIGIT_9: 0x39, + SEMICOLON: 0x3b, + LESS_THAN_SIGN: 0x3c, + EQUALS_SIGN: 0x3d, + GREATER_THAN_SIGN: 0x3e, + QUESTION_MARK: 0x3f, + LATIN_CAPITAL_A: 0x41, + LATIN_CAPITAL_F: 0x46, + LATIN_CAPITAL_X: 0x58, + LATIN_CAPITAL_Z: 0x5a, + RIGHT_SQUARE_BRACKET: 0x5d, + GRAVE_ACCENT: 0x60, + LATIN_SMALL_A: 0x61, + LATIN_SMALL_F: 0x66, + LATIN_SMALL_X: 0x78, + LATIN_SMALL_Z: 0x7a, + REPLACEMENT_CHARACTER: 0xfffd + } - _processInputToken(token) { - mxn.ctLoc = token.location; + exports.CODE_POINT_SEQUENCES = { + DASH_DASH_STRING: [0x2d, 0x2d], //-- + DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE + CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[ + SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script + PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC + SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM + } - orig._processInputToken.call(this, token); - }, + //Surrogates + exports.isSurrogate = function (cp) { + return cp >= 0xd800 && cp <= 0xdfff + } - _err(code, options) { - mxn.locBeforeToken = options && options.beforeToken; - mxn._reportError(code); - } - }; - } -} + exports.isSurrogatePair = function (cp) { + return cp >= 0xdc00 && cp <= 0xdfff + } + + exports.getSurrogatePairCodePoint = function (cp1, cp2) { + return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2 + } + + //NOTE: excluding NULL and ASCII whitespace + exports.isControlCodePoint = function (cp) { + return ( + (cp !== 0x20 && + cp !== 0x0a && + cp !== 0x0d && + cp !== 0x09 && + cp !== 0x0c && + cp >= 0x01 && + cp <= 0x1f) || + (cp >= 0x7f && cp <= 0x9f) + ) + } + + exports.isUndefinedCodePoint = function (cp) { + return ( + (cp >= 0xfdd0 && cp <= 0xfdef) || + UNDEFINED_CODE_POINTS.indexOf(cp) > -1 + ) + } + + /***/ + }, + + /***/ 1842: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' -module.exports = ErrorReportingParserMixin; + const Mixin = __webpack_require__(369) + class ErrorReportingMixinBase extends Mixin { + constructor(host, opts) { + super(host) -/***/ }), + this.posTracker = null + this.onParseError = opts.onParseError + } -/***/ 8918: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + _setErrorLocation(err) { + err.startLine = err.endLine = this.posTracker.line + err.startCol = err.endCol = this.posTracker.col + err.startOffset = err.endOffset = this.posTracker.offset + } -"use strict"; + _reportError(code) { + const err = { + code: code, + startLine: -1, + startCol: -1, + startOffset: -1, + endLine: -1, + endCol: -1, + endOffset: -1 + } + this._setErrorLocation(err) + this.onParseError(err) + } -const ErrorReportingMixinBase = __webpack_require__(1842); -const PositionTrackingPreprocessorMixin = __webpack_require__(1187); -const Mixin = __webpack_require__(369); + _getOverriddenMethods(mxn) { + return { + _err(code) { + mxn._reportError(code) + } + } + } + } -class ErrorReportingPreprocessorMixin extends ErrorReportingMixinBase { - constructor(preprocessor, opts) { - super(preprocessor, opts); + module.exports = ErrorReportingMixinBase - this.posTracker = Mixin.install(preprocessor, PositionTrackingPreprocessorMixin); - this.lastErrOffset = -1; - } + /***/ + }, - _reportError(code) { - //NOTE: avoid reporting error twice on advance/retreat - if (this.lastErrOffset !== this.posTracker.offset) { - this.lastErrOffset = this.posTracker.offset; - super._reportError(code); + /***/ 9203: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + const ErrorReportingMixinBase = __webpack_require__(1842) + const ErrorReportingTokenizerMixin = __webpack_require__(6378) + const LocationInfoTokenizerMixin = __webpack_require__(6091) + const Mixin = __webpack_require__(369) + + class ErrorReportingParserMixin extends ErrorReportingMixinBase { + constructor(parser, opts) { + super(parser, opts) + + this.opts = opts + this.ctLoc = null + this.locBeforeToken = false + } + + _setErrorLocation(err) { + if (this.ctLoc) { + err.startLine = this.ctLoc.startLine + err.startCol = this.ctLoc.startCol + err.startOffset = this.ctLoc.startOffset + + err.endLine = this.locBeforeToken + ? this.ctLoc.startLine + : this.ctLoc.endLine + err.endCol = this.locBeforeToken + ? this.ctLoc.startCol + : this.ctLoc.endCol + err.endOffset = this.locBeforeToken + ? this.ctLoc.startOffset + : this.ctLoc.endOffset + } } - } -} -module.exports = ErrorReportingPreprocessorMixin; + _getOverriddenMethods(mxn, orig) { + return { + _bootstrap(document, fragmentContext) { + orig._bootstrap.call(this, document, fragmentContext) + + Mixin.install( + this.tokenizer, + ErrorReportingTokenizerMixin, + mxn.opts + ) + Mixin.install(this.tokenizer, LocationInfoTokenizerMixin) + }, + + _processInputToken(token) { + mxn.ctLoc = token.location + orig._processInputToken.call(this, token) + }, -/***/ }), + _err(code, options) { + mxn.locBeforeToken = options && options.beforeToken + mxn._reportError(code) + } + } + } + } -/***/ 6378: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + module.exports = ErrorReportingParserMixin -"use strict"; + /***/ + }, + /***/ 8918: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' -const ErrorReportingMixinBase = __webpack_require__(1842); -const ErrorReportingPreprocessorMixin = __webpack_require__(8918); -const Mixin = __webpack_require__(369); + const ErrorReportingMixinBase = __webpack_require__(1842) + const PositionTrackingPreprocessorMixin = __webpack_require__(1187) + const Mixin = __webpack_require__(369) -class ErrorReportingTokenizerMixin extends ErrorReportingMixinBase { - constructor(tokenizer, opts) { - super(tokenizer, opts); + class ErrorReportingPreprocessorMixin extends ErrorReportingMixinBase { + constructor(preprocessor, opts) { + super(preprocessor, opts) - const preprocessorMixin = Mixin.install(tokenizer.preprocessor, ErrorReportingPreprocessorMixin, opts); + this.posTracker = Mixin.install( + preprocessor, + PositionTrackingPreprocessorMixin + ) + this.lastErrOffset = -1 + } - this.posTracker = preprocessorMixin.posTracker; - } -} + _reportError(code) { + //NOTE: avoid reporting error twice on advance/retreat + if (this.lastErrOffset !== this.posTracker.offset) { + this.lastErrOffset = this.posTracker.offset + super._reportError(code) + } + } + } -module.exports = ErrorReportingTokenizerMixin; + module.exports = ErrorReportingPreprocessorMixin + /***/ + }, -/***/ }), + /***/ 6378: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + const ErrorReportingMixinBase = __webpack_require__(1842) + const ErrorReportingPreprocessorMixin = __webpack_require__(8918) + const Mixin = __webpack_require__(369) + + class ErrorReportingTokenizerMixin extends ErrorReportingMixinBase { + constructor(tokenizer, opts) { + super(tokenizer, opts) + + const preprocessorMixin = Mixin.install( + tokenizer.preprocessor, + ErrorReportingPreprocessorMixin, + opts + ) -/***/ 1594: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this.posTracker = preprocessorMixin.posTracker + } + } -"use strict"; + module.exports = ErrorReportingTokenizerMixin + /***/ + }, -const Mixin = __webpack_require__(369); + /***/ 1594: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' -class LocationInfoOpenElementStackMixin extends Mixin { - constructor(stack, opts) { - super(stack); + const Mixin = __webpack_require__(369) - this.onItemPop = opts.onItemPop; - } + class LocationInfoOpenElementStackMixin extends Mixin { + constructor(stack, opts) { + super(stack) - _getOverriddenMethods(mxn, orig) { - return { + this.onItemPop = opts.onItemPop + } + + _getOverriddenMethods(mxn, orig) { + return { pop() { - mxn.onItemPop(this.current); - orig.pop.call(this); + mxn.onItemPop(this.current) + orig.pop.call(this) }, popAllUpToHtmlElement() { - for (let i = this.stackTop; i > 0; i--) { - mxn.onItemPop(this.items[i]); - } + for (let i = this.stackTop; i > 0; i--) { + mxn.onItemPop(this.items[i]) + } - orig.popAllUpToHtmlElement.call(this); + orig.popAllUpToHtmlElement.call(this) }, remove(element) { - mxn.onItemPop(this.current); - orig.remove.call(this, element); + mxn.onItemPop(this.current) + orig.remove.call(this, element) } - }; - } -} - -module.exports = LocationInfoOpenElementStackMixin; - + } + } + } -/***/ }), + module.exports = LocationInfoOpenElementStackMixin -/***/ 2060: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /***/ + }, -"use strict"; + /***/ 2060: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + const Mixin = __webpack_require__(369) + const Tokenizer = __webpack_require__(6386) + const LocationInfoTokenizerMixin = __webpack_require__(6091) + const LocationInfoOpenElementStackMixin = __webpack_require__(1594) + const HTML = __webpack_require__(4734) -const Mixin = __webpack_require__(369); -const Tokenizer = __webpack_require__(6386); -const LocationInfoTokenizerMixin = __webpack_require__(6091); -const LocationInfoOpenElementStackMixin = __webpack_require__(1594); -const HTML = __webpack_require__(4734); + //Aliases + const $ = HTML.TAG_NAMES -//Aliases -const $ = HTML.TAG_NAMES; + class LocationInfoParserMixin extends Mixin { + constructor(parser) { + super(parser) -class LocationInfoParserMixin extends Mixin { - constructor(parser) { - super(parser); + this.parser = parser + this.treeAdapter = this.parser.treeAdapter + this.posTracker = null + this.lastStartTagToken = null + this.lastFosterParentingLocation = null + this.currentToken = null + } - this.parser = parser; - this.treeAdapter = this.parser.treeAdapter; - this.posTracker = null; - this.lastStartTagToken = null; - this.lastFosterParentingLocation = null; - this.currentToken = null; - } + _setStartLocation(element) { + let loc = null - _setStartLocation(element) { - let loc = null; + if (this.lastStartTagToken) { + loc = Object.assign({}, this.lastStartTagToken.location) + loc.startTag = this.lastStartTagToken.location + } - if (this.lastStartTagToken) { - loc = Object.assign({}, this.lastStartTagToken.location); - loc.startTag = this.lastStartTagToken.location; + this.treeAdapter.setNodeSourceCodeLocation(element, loc) } - this.treeAdapter.setNodeSourceCodeLocation(element, loc); - } - - _setEndLocation(element, closingToken) { - const loc = this.treeAdapter.getNodeSourceCodeLocation(element); + _setEndLocation(element, closingToken) { + const loc = this.treeAdapter.getNodeSourceCodeLocation(element) - if (loc) { + if (loc) { if (closingToken.location) { - const ctLoc = closingToken.location; - const tn = this.treeAdapter.getTagName(element); - - // NOTE: For cases like

- First 'p' closes without a closing - // tag and for cases like

- 'p' closes without a closing tag. - const isClosingEndTag = closingToken.type === Tokenizer.END_TAG_TOKEN && tn === closingToken.tagName; - const endLoc = {}; - if (isClosingEndTag) { - endLoc.endTag = Object.assign({}, ctLoc); - endLoc.endLine = ctLoc.endLine; - endLoc.endCol = ctLoc.endCol; - endLoc.endOffset = ctLoc.endOffset; - } else { - endLoc.endLine = ctLoc.startLine; - endLoc.endCol = ctLoc.startCol; - endLoc.endOffset = ctLoc.startOffset; - } + const ctLoc = closingToken.location + const tn = this.treeAdapter.getTagName(element) + + // NOTE: For cases like

- First 'p' closes without a closing + // tag and for cases like

- 'p' closes without a closing tag. + const isClosingEndTag = + closingToken.type === Tokenizer.END_TAG_TOKEN && + tn === closingToken.tagName + const endLoc = {} + if (isClosingEndTag) { + endLoc.endTag = Object.assign({}, ctLoc) + endLoc.endLine = ctLoc.endLine + endLoc.endCol = ctLoc.endCol + endLoc.endOffset = ctLoc.endOffset + } else { + endLoc.endLine = ctLoc.startLine + endLoc.endCol = ctLoc.startCol + endLoc.endOffset = ctLoc.startOffset + } - this.treeAdapter.updateNodeSourceCodeLocation(element, endLoc); + this.treeAdapter.updateNodeSourceCodeLocation(element, endLoc) } + } } - } - _getOverriddenMethods(mxn, orig) { - return { + _getOverriddenMethods(mxn, orig) { + return { _bootstrap(document, fragmentContext) { - orig._bootstrap.call(this, document, fragmentContext); - - mxn.lastStartTagToken = null; - mxn.lastFosterParentingLocation = null; - mxn.currentToken = null; - - const tokenizerMixin = Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); - - mxn.posTracker = tokenizerMixin.posTracker; - - Mixin.install(this.openElements, LocationInfoOpenElementStackMixin, { - onItemPop: function(element) { - mxn._setEndLocation(element, mxn.currentToken); - } - }); + orig._bootstrap.call(this, document, fragmentContext) + + mxn.lastStartTagToken = null + mxn.lastFosterParentingLocation = null + mxn.currentToken = null + + const tokenizerMixin = Mixin.install( + this.tokenizer, + LocationInfoTokenizerMixin + ) + + mxn.posTracker = tokenizerMixin.posTracker + + Mixin.install( + this.openElements, + LocationInfoOpenElementStackMixin, + { + onItemPop: function (element) { + mxn._setEndLocation(element, mxn.currentToken) + } + } + ) }, _runParsingLoop(scriptHandler) { - orig._runParsingLoop.call(this, scriptHandler); - - // NOTE: generate location info for elements - // that remains on open element stack - for (let i = this.openElements.stackTop; i >= 0; i--) { - mxn._setEndLocation(this.openElements.items[i], mxn.currentToken); - } + orig._runParsingLoop.call(this, scriptHandler) + + // NOTE: generate location info for elements + // that remains on open element stack + for (let i = this.openElements.stackTop; i >= 0; i--) { + mxn._setEndLocation( + this.openElements.items[i], + mxn.currentToken + ) + } }, //Token processing _processTokenInForeignContent(token) { - mxn.currentToken = token; - orig._processTokenInForeignContent.call(this, token); + mxn.currentToken = token + orig._processTokenInForeignContent.call(this, token) }, _processToken(token) { - mxn.currentToken = token; - orig._processToken.call(this, token); - - //NOTE: and are never popped from the stack, so we need to updated - //their end location explicitly. - const requireExplicitUpdate = - token.type === Tokenizer.END_TAG_TOKEN && - (token.tagName === $.HTML || (token.tagName === $.BODY && this.openElements.hasInScope($.BODY))); - - if (requireExplicitUpdate) { - for (let i = this.openElements.stackTop; i >= 0; i--) { - const element = this.openElements.items[i]; - - if (this.treeAdapter.getTagName(element) === token.tagName) { - mxn._setEndLocation(element, token); - break; - } - } + mxn.currentToken = token + orig._processToken.call(this, token) + + //NOTE: and are never popped from the stack, so we need to updated + //their end location explicitly. + const requireExplicitUpdate = + token.type === Tokenizer.END_TAG_TOKEN && + (token.tagName === $.HTML || + (token.tagName === $.BODY && + this.openElements.hasInScope($.BODY))) + + if (requireExplicitUpdate) { + for (let i = this.openElements.stackTop; i >= 0; i--) { + const element = this.openElements.items[i] + + if (this.treeAdapter.getTagName(element) === token.tagName) { + mxn._setEndLocation(element, token) + break + } } + } }, //Doctype _setDocumentType(token) { - orig._setDocumentType.call(this, token); - - const documentChildren = this.treeAdapter.getChildNodes(this.document); - const cnLength = documentChildren.length; - - for (let i = 0; i < cnLength; i++) { - const node = documentChildren[i]; - - if (this.treeAdapter.isDocumentTypeNode(node)) { - this.treeAdapter.setNodeSourceCodeLocation(node, token.location); - break; - } + orig._setDocumentType.call(this, token) + + const documentChildren = this.treeAdapter.getChildNodes( + this.document + ) + const cnLength = documentChildren.length + + for (let i = 0; i < cnLength; i++) { + const node = documentChildren[i] + + if (this.treeAdapter.isDocumentTypeNode(node)) { + this.treeAdapter.setNodeSourceCodeLocation( + node, + token.location + ) + break } + } }, //Elements _attachElementToTree(element) { - //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods. - //So we will use token location stored in this methods for the element. - mxn._setStartLocation(element); - mxn.lastStartTagToken = null; - orig._attachElementToTree.call(this, element); + //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods. + //So we will use token location stored in this methods for the element. + mxn._setStartLocation(element) + mxn.lastStartTagToken = null + orig._attachElementToTree.call(this, element) }, _appendElement(token, namespaceURI) { - mxn.lastStartTagToken = token; - orig._appendElement.call(this, token, namespaceURI); + mxn.lastStartTagToken = token + orig._appendElement.call(this, token, namespaceURI) }, _insertElement(token, namespaceURI) { - mxn.lastStartTagToken = token; - orig._insertElement.call(this, token, namespaceURI); + mxn.lastStartTagToken = token + orig._insertElement.call(this, token, namespaceURI) }, _insertTemplate(token) { - mxn.lastStartTagToken = token; - orig._insertTemplate.call(this, token); - - const tmplContent = this.treeAdapter.getTemplateContent(this.openElements.current); - - this.treeAdapter.setNodeSourceCodeLocation(tmplContent, null); - }, - - _insertFakeRootElement() { - orig._insertFakeRootElement.call(this); - this.treeAdapter.setNodeSourceCodeLocation(this.openElements.current, null); - }, - - //Comments - _appendCommentNode(token, parent) { - orig._appendCommentNode.call(this, token, parent); - - const children = this.treeAdapter.getChildNodes(parent); - const commentNode = children[children.length - 1]; - - this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location); - }, - - //Text - _findFosterParentingLocation() { - //NOTE: store last foster parenting location, so we will be able to find inserted text - //in case of foster parenting - mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call(this); - - return mxn.lastFosterParentingLocation; - }, - - _insertCharacters(token) { - orig._insertCharacters.call(this, token); - - const hasFosterParent = this._shouldFosterParentOnInsertion(); - - const parent = - (hasFosterParent && mxn.lastFosterParentingLocation.parent) || - this.openElements.currentTmplContent || - this.openElements.current; + mxn.lastStartTagToken = token + orig._insertTemplate.call(this, token) - const siblings = this.treeAdapter.getChildNodes(parent); - - const textNodeIdx = - hasFosterParent && mxn.lastFosterParentingLocation.beforeElement - ? siblings.indexOf(mxn.lastFosterParentingLocation.beforeElement) - 1 - : siblings.length - 1; - - const textNode = siblings[textNodeIdx]; - - //NOTE: if we have location assigned by another token, then just update end position - const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode); - - if (tnLoc) { - const { endLine, endCol, endOffset } = token.location; - this.treeAdapter.updateNodeSourceCodeLocation(textNode, { endLine, endCol, endOffset }); - } else { - this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location); - } - } - }; - } -} + const tmplContent = this.treeAdapter.getTemplateContent( + this.openElements.current + ) -module.exports = LocationInfoParserMixin; + this.treeAdapter.setNodeSourceCodeLocation(tmplContent, null) + }, + _insertFakeRootElement() { + orig._insertFakeRootElement.call(this) + this.treeAdapter.setNodeSourceCodeLocation( + this.openElements.current, + null + ) + }, -/***/ }), + //Comments + _appendCommentNode(token, parent) { + orig._appendCommentNode.call(this, token, parent) -/***/ 6091: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const children = this.treeAdapter.getChildNodes(parent) + const commentNode = children[children.length - 1] -"use strict"; + this.treeAdapter.setNodeSourceCodeLocation( + commentNode, + token.location + ) + }, + //Text + _findFosterParentingLocation() { + //NOTE: store last foster parenting location, so we will be able to find inserted text + //in case of foster parenting + mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call( + this + ) -const Mixin = __webpack_require__(369); -const Tokenizer = __webpack_require__(6386); -const PositionTrackingPreprocessorMixin = __webpack_require__(1187); + return mxn.lastFosterParentingLocation + }, -class LocationInfoTokenizerMixin extends Mixin { - constructor(tokenizer) { - super(tokenizer); + _insertCharacters(token) { + orig._insertCharacters.call(this, token) + + const hasFosterParent = this._shouldFosterParentOnInsertion() + + const parent = + (hasFosterParent && mxn.lastFosterParentingLocation.parent) || + this.openElements.currentTmplContent || + this.openElements.current + + const siblings = this.treeAdapter.getChildNodes(parent) + + const textNodeIdx = + hasFosterParent && mxn.lastFosterParentingLocation.beforeElement + ? siblings.indexOf( + mxn.lastFosterParentingLocation.beforeElement + ) - 1 + : siblings.length - 1 + + const textNode = siblings[textNodeIdx] + + //NOTE: if we have location assigned by another token, then just update end position + const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode) + + if (tnLoc) { + const { endLine, endCol, endOffset } = token.location + this.treeAdapter.updateNodeSourceCodeLocation(textNode, { + endLine, + endCol, + endOffset + }) + } else { + this.treeAdapter.setNodeSourceCodeLocation( + textNode, + token.location + ) + } + } + } + } + } - this.tokenizer = tokenizer; - this.posTracker = Mixin.install(tokenizer.preprocessor, PositionTrackingPreprocessorMixin); - this.currentAttrLocation = null; - this.ctLoc = null; - } + module.exports = LocationInfoParserMixin - _getCurrentLocation() { - return { + /***/ + }, + + /***/ 6091: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + const Mixin = __webpack_require__(369) + const Tokenizer = __webpack_require__(6386) + const PositionTrackingPreprocessorMixin = __webpack_require__(1187) + + class LocationInfoTokenizerMixin extends Mixin { + constructor(tokenizer) { + super(tokenizer) + + this.tokenizer = tokenizer + this.posTracker = Mixin.install( + tokenizer.preprocessor, + PositionTrackingPreprocessorMixin + ) + this.currentAttrLocation = null + this.ctLoc = null + } + + _getCurrentLocation() { + return { startLine: this.posTracker.line, startCol: this.posTracker.col, startOffset: this.posTracker.offset, endLine: -1, endCol: -1, endOffset: -1 - }; - } + } + } - _attachCurrentAttrLocationInfo() { - this.currentAttrLocation.endLine = this.posTracker.line; - this.currentAttrLocation.endCol = this.posTracker.col; - this.currentAttrLocation.endOffset = this.posTracker.offset; + _attachCurrentAttrLocationInfo() { + this.currentAttrLocation.endLine = this.posTracker.line + this.currentAttrLocation.endCol = this.posTracker.col + this.currentAttrLocation.endOffset = this.posTracker.offset - const currentToken = this.tokenizer.currentToken; - const currentAttr = this.tokenizer.currentAttr; + const currentToken = this.tokenizer.currentToken + const currentAttr = this.tokenizer.currentAttr - if (!currentToken.location.attrs) { - currentToken.location.attrs = Object.create(null); - } + if (!currentToken.location.attrs) { + currentToken.location.attrs = Object.create(null) + } - currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation; - } + currentToken.location.attrs[ + currentAttr.name + ] = this.currentAttrLocation + } - _getOverriddenMethods(mxn, orig) { - const methods = { + _getOverriddenMethods(mxn, orig) { + const methods = { _createStartTagToken() { - orig._createStartTagToken.call(this); - this.currentToken.location = mxn.ctLoc; + orig._createStartTagToken.call(this) + this.currentToken.location = mxn.ctLoc }, _createEndTagToken() { - orig._createEndTagToken.call(this); - this.currentToken.location = mxn.ctLoc; + orig._createEndTagToken.call(this) + this.currentToken.location = mxn.ctLoc }, _createCommentToken() { - orig._createCommentToken.call(this); - this.currentToken.location = mxn.ctLoc; + orig._createCommentToken.call(this) + this.currentToken.location = mxn.ctLoc }, _createDoctypeToken(initialName) { - orig._createDoctypeToken.call(this, initialName); - this.currentToken.location = mxn.ctLoc; + orig._createDoctypeToken.call(this, initialName) + this.currentToken.location = mxn.ctLoc }, _createCharacterToken(type, ch) { - orig._createCharacterToken.call(this, type, ch); - this.currentCharacterToken.location = mxn.ctLoc; + orig._createCharacterToken.call(this, type, ch) + this.currentCharacterToken.location = mxn.ctLoc }, _createEOFToken() { - orig._createEOFToken.call(this); - this.currentToken.location = mxn._getCurrentLocation(); + orig._createEOFToken.call(this) + this.currentToken.location = mxn._getCurrentLocation() }, _createAttr(attrNameFirstCh) { - orig._createAttr.call(this, attrNameFirstCh); - mxn.currentAttrLocation = mxn._getCurrentLocation(); + orig._createAttr.call(this, attrNameFirstCh) + mxn.currentAttrLocation = mxn._getCurrentLocation() }, _leaveAttrName(toState) { - orig._leaveAttrName.call(this, toState); - mxn._attachCurrentAttrLocationInfo(); + orig._leaveAttrName.call(this, toState) + mxn._attachCurrentAttrLocationInfo() }, _leaveAttrValue(toState) { - orig._leaveAttrValue.call(this, toState); - mxn._attachCurrentAttrLocationInfo(); + orig._leaveAttrValue.call(this, toState) + mxn._attachCurrentAttrLocationInfo() }, _emitCurrentToken() { - const ctLoc = this.currentToken.location; - - //NOTE: if we have pending character token make it's end location equal to the - //current token's start location. - if (this.currentCharacterToken) { - this.currentCharacterToken.location.endLine = ctLoc.startLine; - this.currentCharacterToken.location.endCol = ctLoc.startCol; - this.currentCharacterToken.location.endOffset = ctLoc.startOffset; - } + const ctLoc = this.currentToken.location + + //NOTE: if we have pending character token make it's end location equal to the + //current token's start location. + if (this.currentCharacterToken) { + this.currentCharacterToken.location.endLine = ctLoc.startLine + this.currentCharacterToken.location.endCol = ctLoc.startCol + this.currentCharacterToken.location.endOffset = + ctLoc.startOffset + } - if (this.currentToken.type === Tokenizer.EOF_TOKEN) { - ctLoc.endLine = ctLoc.startLine; - ctLoc.endCol = ctLoc.startCol; - ctLoc.endOffset = ctLoc.startOffset; - } else { - ctLoc.endLine = mxn.posTracker.line; - ctLoc.endCol = mxn.posTracker.col + 1; - ctLoc.endOffset = mxn.posTracker.offset + 1; - } + if (this.currentToken.type === Tokenizer.EOF_TOKEN) { + ctLoc.endLine = ctLoc.startLine + ctLoc.endCol = ctLoc.startCol + ctLoc.endOffset = ctLoc.startOffset + } else { + ctLoc.endLine = mxn.posTracker.line + ctLoc.endCol = mxn.posTracker.col + 1 + ctLoc.endOffset = mxn.posTracker.offset + 1 + } - orig._emitCurrentToken.call(this); + orig._emitCurrentToken.call(this) }, _emitCurrentCharacterToken() { - const ctLoc = this.currentCharacterToken && this.currentCharacterToken.location; - - //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(), - //then set it's location at the current preprocessor position. - //We don't need to increment preprocessor position, since character token - //emission is always forced by the start of the next character token here. - //So, we already have advanced position. - if (ctLoc && ctLoc.endOffset === -1) { - ctLoc.endLine = mxn.posTracker.line; - ctLoc.endCol = mxn.posTracker.col; - ctLoc.endOffset = mxn.posTracker.offset; - } + const ctLoc = + this.currentCharacterToken && + this.currentCharacterToken.location + + //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(), + //then set it's location at the current preprocessor position. + //We don't need to increment preprocessor position, since character token + //emission is always forced by the start of the next character token here. + //So, we already have advanced position. + if (ctLoc && ctLoc.endOffset === -1) { + ctLoc.endLine = mxn.posTracker.line + ctLoc.endCol = mxn.posTracker.col + ctLoc.endOffset = mxn.posTracker.offset + } - orig._emitCurrentCharacterToken.call(this); + orig._emitCurrentCharacterToken.call(this) } - }; - - //NOTE: patch initial states for each mode to obtain token start position - Object.keys(Tokenizer.MODE).forEach(modeName => { - const state = Tokenizer.MODE[modeName]; - - methods[state] = function(cp) { - mxn.ctLoc = mxn._getCurrentLocation(); - orig[state].call(this, cp); - }; - }); - - return methods; - } -} + } -module.exports = LocationInfoTokenizerMixin; + //NOTE: patch initial states for each mode to obtain token start position + Object.keys(Tokenizer.MODE).forEach((modeName) => { + const state = Tokenizer.MODE[modeName] + methods[state] = function (cp) { + mxn.ctLoc = mxn._getCurrentLocation() + orig[state].call(this, cp) + } + }) -/***/ }), + return methods + } + } -/***/ 1187: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + module.exports = LocationInfoTokenizerMixin -"use strict"; + /***/ + }, + /***/ 1187: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' -const Mixin = __webpack_require__(369); + const Mixin = __webpack_require__(369) -class PositionTrackingPreprocessorMixin extends Mixin { - constructor(preprocessor) { - super(preprocessor); + class PositionTrackingPreprocessorMixin extends Mixin { + constructor(preprocessor) { + super(preprocessor) - this.preprocessor = preprocessor; - this.isEol = false; - this.lineStartPos = 0; - this.droppedBufferSize = 0; + this.preprocessor = preprocessor + this.isEol = false + this.lineStartPos = 0 + this.droppedBufferSize = 0 - this.offset = 0; - this.col = 0; - this.line = 1; - } + this.offset = 0 + this.col = 0 + this.line = 1 + } - _getOverriddenMethods(mxn, orig) { - return { + _getOverriddenMethods(mxn, orig) { + return { advance() { - const pos = this.pos + 1; - const ch = this.html[pos]; - - //NOTE: LF should be in the last column of the line - if (mxn.isEol) { - mxn.isEol = false; - mxn.line++; - mxn.lineStartPos = pos; - } + const pos = this.pos + 1 + const ch = this.html[pos] + + //NOTE: LF should be in the last column of the line + if (mxn.isEol) { + mxn.isEol = false + mxn.line++ + mxn.lineStartPos = pos + } - if (ch === '\n' || (ch === '\r' && this.html[pos + 1] !== '\n')) { - mxn.isEol = true; - } + if (ch === '\n' || (ch === '\r' && this.html[pos + 1] !== '\n')) { + mxn.isEol = true + } - mxn.col = pos - mxn.lineStartPos + 1; - mxn.offset = mxn.droppedBufferSize + pos; + mxn.col = pos - mxn.lineStartPos + 1 + mxn.offset = mxn.droppedBufferSize + pos - return orig.advance.call(this); + return orig.advance.call(this) }, retreat() { - orig.retreat.call(this); + orig.retreat.call(this) - mxn.isEol = false; - mxn.col = this.pos - mxn.lineStartPos + 1; + mxn.isEol = false + mxn.col = this.pos - mxn.lineStartPos + 1 }, dropParsedChunk() { - const prevPos = this.pos; + const prevPos = this.pos - orig.dropParsedChunk.call(this); + orig.dropParsedChunk.call(this) - const reduction = prevPos - this.pos; + const reduction = prevPos - this.pos - mxn.lineStartPos -= reduction; - mxn.droppedBufferSize += reduction; - mxn.offset = mxn.droppedBufferSize + this.pos; + mxn.lineStartPos -= reduction + mxn.droppedBufferSize += reduction + mxn.offset = mxn.droppedBufferSize + this.pos } - }; - } -} - -module.exports = PositionTrackingPreprocessorMixin; - - -/***/ }), + } + } + } -/***/ 4136: -/***/ ((module) => { + module.exports = PositionTrackingPreprocessorMixin -"use strict"; + /***/ + }, + /***/ 4136: /***/ (module) => { + 'use strict' -//Const -const NOAH_ARK_CAPACITY = 3; + //Const + const NOAH_ARK_CAPACITY = 3 -//List of formatting elements -class FormattingElementList { - constructor(treeAdapter) { - this.length = 0; - this.entries = []; - this.treeAdapter = treeAdapter; - this.bookmark = null; - } + //List of formatting elements + class FormattingElementList { + constructor(treeAdapter) { + this.length = 0 + this.entries = [] + this.treeAdapter = treeAdapter + this.bookmark = null + } - //Noah Ark's condition - //OPTIMIZATION: at first we try to find possible candidates for exclusion using - //lightweight heuristics without thorough attributes check. - _getNoahArkConditionCandidates(newElement) { - const candidates = []; + //Noah Ark's condition + //OPTIMIZATION: at first we try to find possible candidates for exclusion using + //lightweight heuristics without thorough attributes check. + _getNoahArkConditionCandidates(newElement) { + const candidates = [] - if (this.length >= NOAH_ARK_CAPACITY) { - const neAttrsLength = this.treeAdapter.getAttrList(newElement).length; - const neTagName = this.treeAdapter.getTagName(newElement); - const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); + if (this.length >= NOAH_ARK_CAPACITY) { + const neAttrsLength = this.treeAdapter.getAttrList(newElement) + .length + const neTagName = this.treeAdapter.getTagName(newElement) + const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement) for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; + const entry = this.entries[i] - if (entry.type === FormattingElementList.MARKER_ENTRY) { - break; - } + if (entry.type === FormattingElementList.MARKER_ENTRY) { + break + } - const element = entry.element; - const elementAttrs = this.treeAdapter.getAttrList(element); + const element = entry.element + const elementAttrs = this.treeAdapter.getAttrList(element) - const isCandidate = - this.treeAdapter.getTagName(element) === neTagName && - this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && - elementAttrs.length === neAttrsLength; + const isCandidate = + this.treeAdapter.getTagName(element) === neTagName && + this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && + elementAttrs.length === neAttrsLength - if (isCandidate) { - candidates.push({ idx: i, attrs: elementAttrs }); - } + if (isCandidate) { + candidates.push({ idx: i, attrs: elementAttrs }) + } } - } + } - return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates; - } + return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates + } - _ensureNoahArkCondition(newElement) { - const candidates = this._getNoahArkConditionCandidates(newElement); - let cLength = candidates.length; + _ensureNoahArkCondition(newElement) { + const candidates = this._getNoahArkConditionCandidates(newElement) + let cLength = candidates.length - if (cLength) { - const neAttrs = this.treeAdapter.getAttrList(newElement); - const neAttrsLength = neAttrs.length; - const neAttrsMap = Object.create(null); + if (cLength) { + const neAttrs = this.treeAdapter.getAttrList(newElement) + const neAttrsLength = neAttrs.length + const neAttrsMap = Object.create(null) //NOTE: build attrs map for the new element so we can perform fast lookups for (let i = 0; i < neAttrsLength; i++) { - const neAttr = neAttrs[i]; + const neAttr = neAttrs[i] - neAttrsMap[neAttr.name] = neAttr.value; + neAttrsMap[neAttr.name] = neAttr.value } for (let i = 0; i < neAttrsLength; i++) { - for (let j = 0; j < cLength; j++) { - const cAttr = candidates[j].attrs[i]; + for (let j = 0; j < cLength; j++) { + const cAttr = candidates[j].attrs[i] - if (neAttrsMap[cAttr.name] !== cAttr.value) { - candidates.splice(j, 1); - cLength--; - } + if (neAttrsMap[cAttr.name] !== cAttr.value) { + candidates.splice(j, 1) + cLength-- + } - if (candidates.length < NOAH_ARK_CAPACITY) { - return; - } + if (candidates.length < NOAH_ARK_CAPACITY) { + return } + } } //NOTE: remove bottommost candidates until Noah's Ark condition will not be met for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) { - this.entries.splice(candidates[i].idx, 1); - this.length--; + this.entries.splice(candidates[i].idx, 1) + this.length-- } + } } - } - //Mutations - insertMarker() { - this.entries.push({ type: FormattingElementList.MARKER_ENTRY }); - this.length++; - } + //Mutations + insertMarker() { + this.entries.push({ type: FormattingElementList.MARKER_ENTRY }) + this.length++ + } - pushElement(element, token) { - this._ensureNoahArkCondition(element); + pushElement(element, token) { + this._ensureNoahArkCondition(element) - this.entries.push({ + this.entries.push({ type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token - }); + }) - this.length++; - } + this.length++ + } - insertElementAfterBookmark(element, token) { - let bookmarkIdx = this.length - 1; + insertElementAfterBookmark(element, token) { + let bookmarkIdx = this.length - 1 - for (; bookmarkIdx >= 0; bookmarkIdx--) { + for (; bookmarkIdx >= 0; bookmarkIdx--) { if (this.entries[bookmarkIdx] === this.bookmark) { - break; + break } - } + } - this.entries.splice(bookmarkIdx + 1, 0, { + this.entries.splice(bookmarkIdx + 1, 0, { type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token - }); + }) - this.length++; - } + this.length++ + } - removeEntry(entry) { - for (let i = this.length - 1; i >= 0; i--) { + removeEntry(entry) { + for (let i = this.length - 1; i >= 0; i--) { if (this.entries[i] === entry) { - this.entries.splice(i, 1); - this.length--; - break; + this.entries.splice(i, 1) + this.length-- + break } + } } - } - clearToLastMarker() { - while (this.length) { - const entry = this.entries.pop(); + clearToLastMarker() { + while (this.length) { + const entry = this.entries.pop() - this.length--; + this.length-- if (entry.type === FormattingElementList.MARKER_ENTRY) { - break; + break } + } } - } - //Search - getElementEntryInScopeWithTagName(tagName) { - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; + //Search + getElementEntryInScopeWithTagName(tagName) { + for (let i = this.length - 1; i >= 0; i--) { + const entry = this.entries[i] if (entry.type === FormattingElementList.MARKER_ENTRY) { - return null; + return null } if (this.treeAdapter.getTagName(entry.element) === tagName) { - return entry; + return entry } - } + } - return null; - } + return null + } - getElementEntry(element) { - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; + getElementEntry(element) { + for (let i = this.length - 1; i >= 0; i--) { + const entry = this.entries[i] - if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) { - return entry; + if ( + entry.type === FormattingElementList.ELEMENT_ENTRY && + entry.element === element + ) { + return entry } + } + + return null } + } - return null; - } -} - -//Entry types -FormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY'; -FormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY'; - -module.exports = FormattingElementList; - - -/***/ }), - -/***/ 2884: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const Tokenizer = __webpack_require__(6386); -const OpenElementStack = __webpack_require__(2495); -const FormattingElementList = __webpack_require__(4136); -const LocationInfoParserMixin = __webpack_require__(2060); -const ErrorReportingParserMixin = __webpack_require__(9203); -const Mixin = __webpack_require__(369); -const defaultTreeAdapter = __webpack_require__(1301); -const mergeOptions = __webpack_require__(212); -const doctype = __webpack_require__(2169); -const foreignContent = __webpack_require__(4183); -const ERR = __webpack_require__(4068); -const unicode = __webpack_require__(118); -const HTML = __webpack_require__(4734); - -//Aliases -const $ = HTML.TAG_NAMES; -const NS = HTML.NAMESPACES; -const ATTRS = HTML.ATTRS; - -const DEFAULT_OPTIONS = { - scriptingEnabled: true, - sourceCodeLocationInfo: false, - onParseError: null, - treeAdapter: defaultTreeAdapter -}; - -//Misc constants -const HIDDEN_INPUT_TYPE = 'hidden'; - -//Adoption agency loops iteration count -const AA_OUTER_LOOP_ITER = 8; -const AA_INNER_LOOP_ITER = 3; - -//Insertion modes -const INITIAL_MODE = 'INITIAL_MODE'; -const BEFORE_HTML_MODE = 'BEFORE_HTML_MODE'; -const BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE'; -const IN_HEAD_MODE = 'IN_HEAD_MODE'; -const IN_HEAD_NO_SCRIPT_MODE = 'IN_HEAD_NO_SCRIPT_MODE'; -const AFTER_HEAD_MODE = 'AFTER_HEAD_MODE'; -const IN_BODY_MODE = 'IN_BODY_MODE'; -const TEXT_MODE = 'TEXT_MODE'; -const IN_TABLE_MODE = 'IN_TABLE_MODE'; -const IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE'; -const IN_CAPTION_MODE = 'IN_CAPTION_MODE'; -const IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE'; -const IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE'; -const IN_ROW_MODE = 'IN_ROW_MODE'; -const IN_CELL_MODE = 'IN_CELL_MODE'; -const IN_SELECT_MODE = 'IN_SELECT_MODE'; -const IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE'; -const IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE'; -const AFTER_BODY_MODE = 'AFTER_BODY_MODE'; -const IN_FRAMESET_MODE = 'IN_FRAMESET_MODE'; -const AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE'; -const AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE'; -const AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE'; - -//Insertion mode reset map -const INSERTION_MODE_RESET_MAP = { - [$.TR]: IN_ROW_MODE, - [$.TBODY]: IN_TABLE_BODY_MODE, - [$.THEAD]: IN_TABLE_BODY_MODE, - [$.TFOOT]: IN_TABLE_BODY_MODE, - [$.CAPTION]: IN_CAPTION_MODE, - [$.COLGROUP]: IN_COLUMN_GROUP_MODE, - [$.TABLE]: IN_TABLE_MODE, - [$.BODY]: IN_BODY_MODE, - [$.FRAMESET]: IN_FRAMESET_MODE -}; - -//Template insertion mode switch map -const TEMPLATE_INSERTION_MODE_SWITCH_MAP = { - [$.CAPTION]: IN_TABLE_MODE, - [$.COLGROUP]: IN_TABLE_MODE, - [$.TBODY]: IN_TABLE_MODE, - [$.TFOOT]: IN_TABLE_MODE, - [$.THEAD]: IN_TABLE_MODE, - [$.COL]: IN_COLUMN_GROUP_MODE, - [$.TR]: IN_TABLE_BODY_MODE, - [$.TD]: IN_ROW_MODE, - [$.TH]: IN_ROW_MODE -}; - -//Token handlers map for insertion modes -const TOKEN_HANDLERS = { - [INITIAL_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInInitialMode, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInInitialMode, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: doctypeInInitialMode, - [Tokenizer.START_TAG_TOKEN]: tokenInInitialMode, - [Tokenizer.END_TAG_TOKEN]: tokenInInitialMode, - [Tokenizer.EOF_TOKEN]: tokenInInitialMode - }, - [BEFORE_HTML_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHtml, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHtml, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagBeforeHtml, - [Tokenizer.END_TAG_TOKEN]: endTagBeforeHtml, - [Tokenizer.EOF_TOKEN]: tokenBeforeHtml - }, - [BEFORE_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagBeforeHead, - [Tokenizer.END_TAG_TOKEN]: endTagBeforeHead, - [Tokenizer.EOF_TOKEN]: tokenBeforeHead - }, - [IN_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagInHead, - [Tokenizer.END_TAG_TOKEN]: endTagInHead, - [Tokenizer.EOF_TOKEN]: tokenInHead - }, - [IN_HEAD_NO_SCRIPT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInHeadNoScript, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHeadNoScript, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagInHeadNoScript, - [Tokenizer.END_TAG_TOKEN]: endTagInHeadNoScript, - [Tokenizer.EOF_TOKEN]: tokenInHeadNoScript - }, - [AFTER_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagAfterHead, - [Tokenizer.END_TAG_TOKEN]: endTagAfterHead, - [Tokenizer.EOF_TOKEN]: tokenAfterHead - }, - [IN_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInBody, - [Tokenizer.END_TAG_TOKEN]: endTagInBody, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [TEXT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: ignoreToken, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: ignoreToken, - [Tokenizer.END_TAG_TOKEN]: endTagInText, - [Tokenizer.EOF_TOKEN]: eofInText - }, - [IN_TABLE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTable, - [Tokenizer.END_TAG_TOKEN]: endTagInTable, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TABLE_TEXT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTableText, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInTableText, - [Tokenizer.COMMENT_TOKEN]: tokenInTableText, - [Tokenizer.DOCTYPE_TOKEN]: tokenInTableText, - [Tokenizer.START_TAG_TOKEN]: tokenInTableText, - [Tokenizer.END_TAG_TOKEN]: tokenInTableText, - [Tokenizer.EOF_TOKEN]: tokenInTableText - }, - [IN_CAPTION_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInCaption, - [Tokenizer.END_TAG_TOKEN]: endTagInCaption, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_COLUMN_GROUP_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInColumnGroup, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInColumnGroup, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInColumnGroup, - [Tokenizer.END_TAG_TOKEN]: endTagInColumnGroup, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TABLE_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTableBody, - [Tokenizer.END_TAG_TOKEN]: endTagInTableBody, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_ROW_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInRow, - [Tokenizer.END_TAG_TOKEN]: endTagInRow, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_CELL_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInCell, - [Tokenizer.END_TAG_TOKEN]: endTagInCell, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_SELECT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInSelect, - [Tokenizer.END_TAG_TOKEN]: endTagInSelect, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_SELECT_IN_TABLE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInSelectInTable, - [Tokenizer.END_TAG_TOKEN]: endTagInSelectInTable, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TEMPLATE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTemplate, - [Tokenizer.END_TAG_TOKEN]: endTagInTemplate, - [Tokenizer.EOF_TOKEN]: eofInTemplate - }, - [AFTER_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterBody, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToRootHtmlElement, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterBody, - [Tokenizer.END_TAG_TOKEN]: endTagAfterBody, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [IN_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInFrameset, - [Tokenizer.END_TAG_TOKEN]: endTagInFrameset, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterFrameset, - [Tokenizer.END_TAG_TOKEN]: endTagAfterFrameset, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_AFTER_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterAfterBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterAfterBody, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterBody, - [Tokenizer.END_TAG_TOKEN]: tokenAfterAfterBody, - [Tokenizer.EOF_TOKEN]: stopParsing + //Entry types + FormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY' + FormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY' + + module.exports = FormattingElementList + + /***/ }, - [AFTER_AFTER_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterFrameset, - [Tokenizer.END_TAG_TOKEN]: ignoreToken, - [Tokenizer.EOF_TOKEN]: stopParsing - } -}; -//Parser -class Parser { - constructor(options) { - this.options = mergeOptions(DEFAULT_OPTIONS, options); + /***/ 2884: /***/ ( + module, + __unused_webpack_exports, + __webpack_require__ + ) => { + 'use strict' + + const Tokenizer = __webpack_require__(6386) + const OpenElementStack = __webpack_require__(2495) + const FormattingElementList = __webpack_require__(4136) + const LocationInfoParserMixin = __webpack_require__(2060) + const ErrorReportingParserMixin = __webpack_require__(9203) + const Mixin = __webpack_require__(369) + const defaultTreeAdapter = __webpack_require__(1301) + const mergeOptions = __webpack_require__(212) + const doctype = __webpack_require__(2169) + const foreignContent = __webpack_require__(4183) + const ERR = __webpack_require__(4068) + const unicode = __webpack_require__(118) + const HTML = __webpack_require__(4734) + + //Aliases + const $ = HTML.TAG_NAMES + const NS = HTML.NAMESPACES + const ATTRS = HTML.ATTRS + + const DEFAULT_OPTIONS = { + scriptingEnabled: true, + sourceCodeLocationInfo: false, + onParseError: null, + treeAdapter: defaultTreeAdapter + } - this.treeAdapter = this.options.treeAdapter; - this.pendingScript = null; + //Misc constants + const HIDDEN_INPUT_TYPE = 'hidden' + + //Adoption agency loops iteration count + const AA_OUTER_LOOP_ITER = 8 + const AA_INNER_LOOP_ITER = 3 + + //Insertion modes + const INITIAL_MODE = 'INITIAL_MODE' + const BEFORE_HTML_MODE = 'BEFORE_HTML_MODE' + const BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE' + const IN_HEAD_MODE = 'IN_HEAD_MODE' + const IN_HEAD_NO_SCRIPT_MODE = 'IN_HEAD_NO_SCRIPT_MODE' + const AFTER_HEAD_MODE = 'AFTER_HEAD_MODE' + const IN_BODY_MODE = 'IN_BODY_MODE' + const TEXT_MODE = 'TEXT_MODE' + const IN_TABLE_MODE = 'IN_TABLE_MODE' + const IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE' + const IN_CAPTION_MODE = 'IN_CAPTION_MODE' + const IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE' + const IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE' + const IN_ROW_MODE = 'IN_ROW_MODE' + const IN_CELL_MODE = 'IN_CELL_MODE' + const IN_SELECT_MODE = 'IN_SELECT_MODE' + const IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE' + const IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE' + const AFTER_BODY_MODE = 'AFTER_BODY_MODE' + const IN_FRAMESET_MODE = 'IN_FRAMESET_MODE' + const AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE' + const AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE' + const AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE' + + //Insertion mode reset map + const INSERTION_MODE_RESET_MAP = { + [$.TR]: IN_ROW_MODE, + [$.TBODY]: IN_TABLE_BODY_MODE, + [$.THEAD]: IN_TABLE_BODY_MODE, + [$.TFOOT]: IN_TABLE_BODY_MODE, + [$.CAPTION]: IN_CAPTION_MODE, + [$.COLGROUP]: IN_COLUMN_GROUP_MODE, + [$.TABLE]: IN_TABLE_MODE, + [$.BODY]: IN_BODY_MODE, + [$.FRAMESET]: IN_FRAMESET_MODE + } - if (this.options.sourceCodeLocationInfo) { - Mixin.install(this, LocationInfoParserMixin); - } + //Template insertion mode switch map + const TEMPLATE_INSERTION_MODE_SWITCH_MAP = { + [$.CAPTION]: IN_TABLE_MODE, + [$.COLGROUP]: IN_TABLE_MODE, + [$.TBODY]: IN_TABLE_MODE, + [$.TFOOT]: IN_TABLE_MODE, + [$.THEAD]: IN_TABLE_MODE, + [$.COL]: IN_COLUMN_GROUP_MODE, + [$.TR]: IN_TABLE_BODY_MODE, + [$.TD]: IN_ROW_MODE, + [$.TH]: IN_ROW_MODE + } - if (this.options.onParseError) { - Mixin.install(this, ErrorReportingParserMixin, { onParseError: this.options.onParseError }); + //Token handlers map for insertion modes + const TOKEN_HANDLERS = { + [INITIAL_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenInInitialMode, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInInitialMode, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: doctypeInInitialMode, + [Tokenizer.START_TAG_TOKEN]: tokenInInitialMode, + [Tokenizer.END_TAG_TOKEN]: tokenInInitialMode, + [Tokenizer.EOF_TOKEN]: tokenInInitialMode + }, + [BEFORE_HTML_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHtml, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHtml, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagBeforeHtml, + [Tokenizer.END_TAG_TOKEN]: endTagBeforeHtml, + [Tokenizer.EOF_TOKEN]: tokenBeforeHtml + }, + [BEFORE_HEAD_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHead, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHead, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, + [Tokenizer.START_TAG_TOKEN]: startTagBeforeHead, + [Tokenizer.END_TAG_TOKEN]: endTagBeforeHead, + [Tokenizer.EOF_TOKEN]: tokenBeforeHead + }, + [IN_HEAD_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenInHead, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHead, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, + [Tokenizer.START_TAG_TOKEN]: startTagInHead, + [Tokenizer.END_TAG_TOKEN]: endTagInHead, + [Tokenizer.EOF_TOKEN]: tokenInHead + }, + [IN_HEAD_NO_SCRIPT_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenInHeadNoScript, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHeadNoScript, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, + [Tokenizer.START_TAG_TOKEN]: startTagInHeadNoScript, + [Tokenizer.END_TAG_TOKEN]: endTagInHeadNoScript, + [Tokenizer.EOF_TOKEN]: tokenInHeadNoScript + }, + [AFTER_HEAD_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenAfterHead, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterHead, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, + [Tokenizer.START_TAG_TOKEN]: startTagAfterHead, + [Tokenizer.END_TAG_TOKEN]: endTagAfterHead, + [Tokenizer.EOF_TOKEN]: tokenAfterHead + }, + [IN_BODY_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInBody, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInBody, + [Tokenizer.END_TAG_TOKEN]: endTagInBody, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [TEXT_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.NULL_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: ignoreToken, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: ignoreToken, + [Tokenizer.END_TAG_TOKEN]: endTagInText, + [Tokenizer.EOF_TOKEN]: eofInText + }, + [IN_TABLE_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInTable, + [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInTable, + [Tokenizer.END_TAG_TOKEN]: endTagInTable, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_TABLE_TEXT_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInTableText, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInTableText, + [Tokenizer.COMMENT_TOKEN]: tokenInTableText, + [Tokenizer.DOCTYPE_TOKEN]: tokenInTableText, + [Tokenizer.START_TAG_TOKEN]: tokenInTableText, + [Tokenizer.END_TAG_TOKEN]: tokenInTableText, + [Tokenizer.EOF_TOKEN]: tokenInTableText + }, + [IN_CAPTION_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInBody, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInCaption, + [Tokenizer.END_TAG_TOKEN]: endTagInCaption, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_COLUMN_GROUP_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenInColumnGroup, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInColumnGroup, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInColumnGroup, + [Tokenizer.END_TAG_TOKEN]: endTagInColumnGroup, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_TABLE_BODY_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInTable, + [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInTableBody, + [Tokenizer.END_TAG_TOKEN]: endTagInTableBody, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_ROW_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInTable, + [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInRow, + [Tokenizer.END_TAG_TOKEN]: endTagInRow, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_CELL_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInBody, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInCell, + [Tokenizer.END_TAG_TOKEN]: endTagInCell, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_SELECT_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInSelect, + [Tokenizer.END_TAG_TOKEN]: endTagInSelect, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_SELECT_IN_TABLE_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInSelectInTable, + [Tokenizer.END_TAG_TOKEN]: endTagInSelectInTable, + [Tokenizer.EOF_TOKEN]: eofInBody + }, + [IN_TEMPLATE_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: characterInBody, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInTemplate, + [Tokenizer.END_TAG_TOKEN]: endTagInTemplate, + [Tokenizer.EOF_TOKEN]: eofInTemplate + }, + [AFTER_BODY_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenAfterBody, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterBody, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendCommentToRootHtmlElement, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagAfterBody, + [Tokenizer.END_TAG_TOKEN]: endTagAfterBody, + [Tokenizer.EOF_TOKEN]: stopParsing + }, + [IN_FRAMESET_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagInFrameset, + [Tokenizer.END_TAG_TOKEN]: endTagInFrameset, + [Tokenizer.EOF_TOKEN]: stopParsing + }, + [AFTER_FRAMESET_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, + [Tokenizer.COMMENT_TOKEN]: appendComment, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagAfterFrameset, + [Tokenizer.END_TAG_TOKEN]: endTagAfterFrameset, + [Tokenizer.EOF_TOKEN]: stopParsing + }, + [AFTER_AFTER_BODY_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: tokenAfterAfterBody, + [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterAfterBody, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterBody, + [Tokenizer.END_TAG_TOKEN]: tokenAfterAfterBody, + [Tokenizer.EOF_TOKEN]: stopParsing + }, + [AFTER_AFTER_FRAMESET_MODE]: { + [Tokenizer.CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, + [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, + [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, + [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, + [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterFrameset, + [Tokenizer.END_TAG_TOKEN]: ignoreToken, + [Tokenizer.EOF_TOKEN]: stopParsing } - } + } - // API - parse(html) { - const document = this.treeAdapter.createDocument(); + //Parser + class Parser { + constructor(options) { + this.options = mergeOptions(DEFAULT_OPTIONS, options) - this._bootstrap(document, null); - this.tokenizer.write(html, true); - this._runParsingLoop(null); + this.treeAdapter = this.options.treeAdapter + this.pendingScript = null - return document; - } + if (this.options.sourceCodeLocationInfo) { + Mixin.install(this, LocationInfoParserMixin) + } - parseFragment(html, fragmentContext) { - //NOTE: use